If and only if a URL is exactly X than do stuff

What is the vanilla JavaScript way to do an action if and only if we match a URL exactly as-is?

For example,
only if we match https://example.com but not https://www.example.com.

I don’t think that the contains() method is right way here because then everything that contains https://example.com (even things like https://example.com/page/1) would also be targeted.

if (location.href.startsWith('https://example.com')) {
     // do stuff

Thank you for trying to help.
I am not sure that this is what I seek — please have a look in the edit to my question.


if (location.href === 'https://example.com') { ... }

Just for the sake of testing I tried this already:

if (window.location.href === "https://example.com") {

But it didn’t work, output is:


That means location.href contains something different, add console.log(location.href) to check it. Maybe there is a trailing slash

Sorry, I don’t understand.

This also outputs undefined:

if (location.href === "https://example.com") {

What’s inside location.href on the page where you run this?

You probably need to just add a trailing slash:

if (location.href === "https://example.com/") { ... }

console.log(location.href); in the relevant website tested in Google Chrome brought:


Adding a trailing as in:

if (location.href === "https://example.com/") {

Still outputs undefined.

I’m pretty sure there is something else not related to this check of location.href after these three lines of code that’s outputting the “undefined”. You might change it to:

if (location.href == "https://example.com/") {

to clarify what’s happening.

1 Like

Thanks !
Your code, with added } { for the else helped me to debug.

Indeed, in the actual website on which I tested my original code, there was an added Cname (www.) in the URL, which for some reason, didn’t appear in the browser’s URL bar.

So, to sum it all up, my problem was due to two things:

  1. The lack of a trailing slash as discussed above
  2. The existence of an “elusive” Cname (www.) in the URL which I found with the test you suggested

I thank both @veocode and @tracknut for their help.

1 Like
if(/^https:////example.com$/.test(location.href) {
// do something

Only if location.href === “https://example.com” will it do something.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.