user7601186
user7601186

Reputation:

How to check whether URL only contains the domain using javascript?

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

Upvotes: 2

Views: 4343

Answers (3)

Mohammad
Mohammad

Reputation: 21489

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

Upvotes: 2

Artyom Amiryan
Artyom Amiryan

Reputation: 2966

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); // "/"

Upvotes: 3

nircraft
nircraft

Reputation: 8478

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
}

Upvotes: 0

Related Questions