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
3 Answers
Reset to default 3You 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
}