1

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
Mohammad
  • 21,175
  • 15
  • 55
  • 84

3 Answers3

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); // "/"
Artyom Amiryan
  • 2,846
  • 1
  • 10
  • 22
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'));  
Mohammad
  • 21,175
  • 15
  • 55
  • 84
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
}
nircraft
  • 8,242
  • 5
  • 30
  • 46
  • Note this assumes that the string OP wants to check is based on current location rather than some variable input – charlietfl Nov 11 '18 at 14:59