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.
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.
Share Improve this question asked Sep 26, 2011 at 17:17 stevesteve 6886 gold badges13 silver badges32 bronze badges6 Answers
Reset to default 14You 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're searching for a value in the QueryString, you can try this:
var searchIndex = window.location.search.indexOf("nature");
Otherwise, you can do this:
var searchIndex = window.location.href.indexOf("nature");
You can also do this:
var searchIndex = window.location.href.search("/nature/");
To check whether the word was found, you can do this:
if (searchIndex > -1)
//logic here
I think this one should give you a good starting point. JSFiddle is available here.
<div id="test">Some text</div>
.red
{
background-color: #FF0000;
}
function handler( url, textToMatch, objectToChange, classToAssign )
{
if (url.search(textToMatch) != -1)
{
objectToChange.className = classToAssign;
}
}
var url = 'http://www.some-place.com&nature'; //window.location.href in your case
var div = document.getElementById('test');
handler(url, 'nature', div, 'red');
The hash in the URL caused issues for me, so instead I used a "?".
As an example lets say I have the URL: http://example.com?someString
First I retrieved the URL:
var activeURL = window.location.href;
Then I take everything from the index of "?" + 1(because I do not care to include "?") onward.
var activeItem = aactiveURL.substring(activeUrl.indexOf('?') + 1, activeURL.length);
activeItem will be "someString"