I have a function that I want to run when a specific URL path is visited, but there’s other pages further down that path, where I don’t want the script to run. For example:
website.com/names **This is the only URL where the script should run**
website.com/names/24/places
website.com/names/648/groups
website.com/names/7340/questions
The number following “/names/” ranges in length between 1 & n, but the three latter examples are the only further paths the URL might take. I only want the script to run when a user is on the “website.com/names” page, without anything following “pages.” As of right now, I have the function as an “if” statement based on document.URL.indexOf, but it feels a bit messy:
if(document.URL.indexOf("names") >= 0 && (document.URL.indexOf("places") == -1 && document.URL.indexOf("groups") == -1 && document.URL.indexOf("questions") == -1))
This works perfectly fine, but I have a nagging suspicion that there’s probably a better/cleaner way to create the “if” statement. Is there a way to either condense my current line, or use different code that will do the same thing in a simpler way, without over-complicating things?
There are cases regular expressions should be used 🙂
This condition passes only when “names” is the last part of the URL, without anything following it. The
$means matching the end of the string.