Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery if Location.Pathname contains

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

like image 824
SBM Avatar asked Oct 19 '13 01:10

SBM


People also ask

How do you check if the URL contains a given string in jQuery?

How do you check if the URL contains a given string in jQuery? Whether you are using jQuery or JavaScript for your frontend, you can simply use the indexOf() method with the href property using windows. The method indexOf() returns the position (a number) of the first occurrence of a given string.

How do you check if a URL contains a string?

To check if the current URL contains a string in Javascript, you can apply the “test()” method along with the “window. location. href” property for matching the particular string value with the URL or the “toString(). includes()”, or the “indexOf()” method to return the index of the first value in the specified string.

What is Location pathname?

pathname. The pathname property of the Location interface is a string containing the path of the URL for the location. If there is no path, pathname will be empty: otherwise, pathname contains an initial '/' followed by the path of the URL, not including the query string or fragment.

How do I check if a word has a URL?

Method 1: strpos() Function: The strpos() function is used to find the first occurrence of a sub string in a string. If sub string exists then the function returns the starting index of the sub string else returns False if the sub string is not found in the string (URL).


2 Answers

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

if (document.location.pathname.indexOf("/about/") == 0) {
    //Code goes here
}
like image 132
Arun P Johny Avatar answered Oct 11 '22 14:10

Arun P Johny


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

This will check to make sure the pathname always starts with that string. If you are interested in checking the format more specifically, you will need to use regex.

like image 40
marteljn Avatar answered Oct 11 '22 15:10

marteljn