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
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.
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.
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.
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).
use indexOf - it will test true for all pathnames starting with /about/
if (document.location.pathname.indexOf("/about/") == 0) {
//Code goes here
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With