【问题标题】:How to check whether URL only contains the domain using javascript?如何检查 URL 是否仅包含使用 javascript 的域?
【发布时间】:2018-11-11 14:35:50
【问题描述】:

如何检查 url 是否只包含 javascript 中的域?

let s = 'some url string';

必须像下面这样工作。

https://google.com/ --> true
https://docs.google.com/ --> true

https://google.com/blabla  --> false
https://google.com/blabla/ ---> false
https://docs.google.com/blabla/ ---> false

【问题讨论】:

  • 在此处使用 Window.location.href 您将获得完整的 url 作为数组(可能是),然后您可以拆分它并检查您需要检查的内容
  • 你能给我举个例子吗?
  • "http://google.com".includes("google") // true
  • 不,任何不是 google.com 的网址

标签: javascript string url


【解决方案1】:

您可以使用全局URL

const url = new URL('', 'https://google.com/blabla ');
console.log(url.hostname); // "google.com"
console.log(url.pathname); // "/blabla" 

可以查看url.pathname,如果没有路径名,则返回/

const url = new URL('', 'https://google.com ');
console.log(url.hostname); // "google.com"
console.log(url.pathname); // "/"

【讨论】:

  • 请注意,Internet Explorer 不支持URL
【解决方案2】:

您可以使用正则表达式来检查 URL 内容。 /^https?:\/\/[^\/?]+\/$/g 匹配任何以 http 开头并以域后缀和 / 结尾的 URL

var url = 'https://google.com/';
/^https?:\/\/[^\/?]+\/$/g.test(url) // true

function testURL(url){
  return /^https?:\/\/[^\/?]+\/$/g.test(url);
}
console.log(testURL('https://google.com/'));
console.log(testURL('https://docs.google.com/'));
console.log(testURL('https://google.com/blabla'));  

【讨论】:

    【解决方案3】:

    您可以使用Window.location 获取所有这些详细信息

    例如:对于这个问题:

    window.location.hostname  ==>> // "stackoverflow.com"
    
    window.location.pathname == >> ///questions/53249750/how-to-check-whether-url-only-contains-the-domain-in-js
    
    window.location.href == >>
    "https://stackoverflow.com/questions/53249750/how-to-check-whether-url-only- 
     contains-the-domain-in-js"
    

    您可以检查 pathName 并执行您的操作:

    if (window.location.pathname === "" || window.location.pathname === "/") {
       return true
    }
    

    【讨论】:

    • 请注意,这假设 OP 要检查的字符串是基于当前位置而不是某些变量输入
    猜你喜欢
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2021-12-10
    • 2018-04-29
    • 2012-08-02
    • 2011-12-02
    • 2011-05-21
    相关资源
    最近更新 更多