如何使用JavaScript检查URL是否仅包含域?

时间:2018-11-11 14:35:50

标签: javascript string url

如何检查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

3 个答案:

答案 0 :(得分:1)

您可以使用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
}

答案 1 :(得分: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); // "/"

答案 2 :(得分:0)

您可以使用正则表达式检查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'));