I just need a simple function that will search the current url for a string (ie "nature") and then will add a class to an object. I keep finding ways to search the query, but I want to search the entire url. If possible, without jQuery. If not, jQuery will work.
You can get the URL with window.location.href
, and search it however you like:
var location = window.location.href;
if(location.indexOf("whatever") > -1) {
//Do stuff
}
window.location
returns a Location
object, which has a property href
containing the entire URL of the page.
The most basic approach is something like this:
window.location.href.indexOf('nature')
That will return -1
if the string is not found. Otherwise, it returns the index of the string inside the URL string.
Using regexes, as an alternative:
if (window.location.toString().match(/nature/)) {
yourobj.className = 'newclass';
}
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