1

I am trying to track a page visit when someone lands on a search results page. Right now I have an isMatch function, and if it returns true, then it sends an event.

Is there a way to check against window.location.pathname, to basically check whether or not it ends with /search?? Here is an example URL when someone searches:

https://website.com/en_US/search?q=testin&search-button=&lang=en_US

Where "testin" is what the user inputted in the search bar.

Right now, I have:

isMatch: () => {
            const urlParams = new URLSearchParams(window.location.search);
            const paramValue = urlParams.get("q");
            return paramValue !== null && window.location.pathname === "/en_US/search";

However I want to check against if it ends with search so I don't have to include the locale (en_US) since we want to track this on multiple countries without having the change the code. Would something like window.location.hash work? I am not totally familiar with it.

  • Also see: [Check if URL ends with specific string?](https://stackoverflow.com/questions/49767662/check-if-url-ends-with-specific-string) – showdev Feb 06 '23 at 05:23

2 Answers2

2

You can use these two methods to handle it:

  1. endWith()
    return window.location.pathname.endsWith("/search");

Please Note that endsWith() is not supported in IE 11 (or earlier versions)

  1. substring()
    let path= window.location.pathname;
    return path.substring(path.length-7) === "/search";
1

In JavaScript, strings have the method endsWith, which works as you'd expect.

window.location.pathname.endsWith("/search");
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34