最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

simple javascript: search url for string, do something - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a comment  | 

6 Answers 6

Reset to default 14

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'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"

发布评论

评论列表(0)

  1. 暂无评论