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

How can I check whether url only contains the domain in javascript?let s = 'some url string';

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
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745240695a4618165.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信