tags:

views:

149

answers:

1

Hi everyone,

Simply I have a bunch of links like so

<div id="categoryLinks">
    <a href="blah.php?something=this&category=21"></a>
    <a href="blah.php?something=that&category=21"></a>
    <a href="blah.php?something=then&category=21"></a>
</div>

What I'd like to be able to do however, is go through all those links and remove the end bit '&category=21' should I choose to so they would all look like:

<div id="categoryLinks">
    <a href="blah.php?something=this"></a>
    <a href="blah.php?something=that"></a>
    <a href="blah.php?something=then"></a>
</div>

So I'm working on the function that looks something like this:

function removeCategory(){

    $('#categoryLinks a').each(function(){

        // as you can see, i don't know what goes in here!   

});


}

I know how to do the opposite, which is to append a category to the href, but as far as taking it off I am drawing a blank.

How do I do this?

+4  A: 

This will strip all parameters

$('a[href*=?]').each(function () {
    var href = $(this).attr('href');
    $(this).attr('href', href.substring(0, href.indexOf('?'));
});

This will strip particular one

$("a[href*='category=']").each(function () {
    var href = $(this).attr('href');
    $(this).attr('href', href.replace(/&?category=\d+/, ''));
});

a[href*='category='] looks for an category= string in href attribute of a tag. Then this atrribute along with coresponding value is replaced with empty string.

RaYell
good approach, especially with regards to regular expressions. 2 notes however - you should use quotes when selecting for attributes (or parts thereof) with characters like '=' and perhaps an explanation of how your code works would be good.
Darko Z
jQuery attribute selectors works well without quotes as well.
RaYell
wow... is href.replace a jquery function?? *googles*
cosmicbdog
@cosmicbdog you don't know much about JS variables, do you?
RaYell
ha. no, not really. Hey this is working a treat, but it seems on IE a user reported it not working. Does the above code have any compatibility issues with internet explorer?
cosmicbdog
It shouldn't have. Do you have more details on the issue?
RaYell
Sorry to bother you man. I sorted it. It was my fault as usual.
cosmicbdog