2

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.com/ --> true
https://docs.google.com/ --> true

https://google.com/blabla  --> false
https://google.com/blabla/ ---> false
https://docs.google.com/blabla/ ---> false
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 Commented Nov 11, 2018 at 14:40
  • can you provide me the example? Commented Nov 11, 2018 at 14:41
  • "http://google.com".includes("google") // true Commented Nov 11, 2018 at 14:46
  • no, any url not the google.com Commented Nov 11, 2018 at 14:48
  • Possible duplicate of What is a good regular expression to match a URL? Commented Nov 11, 2018 at 14:56

3 Answers 3

3

You can use the global URL:

const url = new URL('', 'https://google.com/blabla ');
console.log(url.hostname); // "google.com"
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.com ');
console.log(url.hostname); // "google.com"
console.log(url.pathname); // "/"
Sign up to request clarification or add additional context in comments.

1 Comment

Note that URL is not supported by internet explorer.
2

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.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'));  

Comments

0

You Can use Window.location to get all these details

Ex: for this question:

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"

You can check for pathName and do your thing:

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

1 Comment

Note this assumes that the string OP wants to check is based on current location rather than some variable input

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.