javascriptpathwindow.locationurlsearchparams

how to check whether window.location.pathname ends with /search?


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.


Solution

  • 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";