user1636946
user1636946

Reputation: 145

How do I get an if statement with window.location.pathname in JS/Jquery to not include anything after the pathname?

I am trying to get this URL "http://www.example.com/womens-collection/ceramic" to redirect to a URL, "http://www.example.com/the-ceramic". Below is the code

   if(window.location.pathname == "/womens-collection/ceramic") {
   //alert("worked");
   document.location = "/the-ceramic";
   //$('#jbw-spot-mobile_details').toggleClass('opened')}

Works fine but I do not want any of the other URLs that are products to be affected by this like "http://www.example.com/womens-collection/ceramic?page=shop.product_details"

How can I get jquery to only recognize "/womens-collection/ceramic" and not anything after that?

Upvotes: 1

Views: 8178

Answers (2)

Gromer
Gromer

Reputation: 9931

regex = /(/womens-collection/ceramic)$/i; // Using the i flag for case insensitivity. Feel free to remove if you want.
path = window.location.pathname;
if (path.match(regex)) {
   // Do stuff.
}

Just using regex to match at the end of the path.

Upvotes: 2

Paul Fleming
Paul Fleming

Reputation: 24526

window.location.search returns the QS portion.

if(window.location.pathname == "/womens-collection/ceramic")
{
    if(!window.location.search)
    {
        // do your thing
    }
}

Upvotes: 1

Related Questions