最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

string - How to check whether URL only contains the domain using javascript? - Stack Overflow

programmeradmin1浏览0评论

How can I check whether url only contains the domain in javascript?

let s = 'some url string';

that must be working like below.

/ --> true
/ --> true

  --> false
/ ---> false
/ ---> false

How can I check whether url only contains the domain in javascript?

let s = 'some url string';

that must be working like below.

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

https://google./blabla  --> false
https://google./blabla/ ---> false
https://docs.google./blabla/ ---> false
Share Improve this question edited Nov 11, 2018 at 15:34 Mohammad 21.5k16 gold badges57 silver badges85 bronze badges asked Nov 11, 2018 at 14:35 user7601186user7601186 5
  • Use Window.location.href there u will get the full url as array (may be ) then u can split it and check what u need to check – sayalok Commented Nov 11, 2018 at 14:40
  • can you provide me the example? – user7601186 Commented Nov 11, 2018 at 14:41
  • "http://google.".includes("google") // true – Jonas Wilms Commented Nov 11, 2018 at 14:46
  • no, any url not the google. – user7601186 Commented Nov 11, 2018 at 14:48
  • Possible duplicate of What is a good regular expression to match a URL? – node_modules Commented Nov 11, 2018 at 14:56
Add a ment  | 

3 Answers 3

Reset to default 3

You can use the global URL:

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

You can check url.pathname, and if there is no pathname, it will return /.

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

You can use regex to check URLs content. The /^https?:\/\/[^\/?]+\/$/g match any URL that start with http and end with domain suffix and /

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

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

You Can use Window.location to get all these details

Ex: for this question:

window.location.hostname  ==>> // "stackoverflow."

window.location.pathname == >> ///questions/53249750/how-to-check-whether-url-only-contains-the-domain-in-js

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

You can check for pathName and do your thing:

if (window.location.pathname === "" || window.location.pathname === "/") {
   return true
}
发布评论

评论列表(0)

  1. 暂无评论