jQuery if Location.Pathname contains

SBM picture SBM · Oct 19, 2013 · Viewed 19.6k times · Source

I am currently using the following code to target individual pages such as http://my-website.com/about/

    if (document.location.pathname == "/about/") {
        //Code goes here
    }

I am wondering how to do the same for all pages that have a certain parent page such as /about/in the following examples..

http://my-website.com/about/child-page1

http://my-website.com/about/child-page2

Answer

Arun P Johny picture Arun P Johny · Oct 19, 2013

use indexOf - it will test true for all pathnames starting with /about/

if (document.location.pathname.indexOf("/about/") == 0) {
    //Code goes here
}