Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple javascript: search url for string, do something

Tags:

javascript

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.

like image 541
steve Avatar asked Sep 26 '11 17:09

steve


3 Answers

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.

like image 155
James Allardice Avatar answered Nov 15 '22 14:11

James Allardice


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.

like image 36
bfavaretto Avatar answered Nov 15 '22 15:11

bfavaretto


Using regexes, as an alternative:

if (window.location.toString().match(/nature/)) {
    yourobj.className = 'newclass';
}
like image 35
Marc B Avatar answered Nov 15 '22 16:11

Marc B