2

I know there are a lot of questions about this, but I didnt found exactly what I needed

This is the js I have

$j('.showCategory li a').each(function() {
    var catId = $j(this).attr("data-id");
    this.href += (/\?/.test(this.href) ? '&' : '?') + 'filter_category='+ catId;
});

This works great as it generate my url with the param I want. The problem is that if I click multiple times (this filter is available on all pages), it's adding the same parameter over and over, generating an url like this:

http://www.blabla.com/search?search=cat&filter_duration=short&filter_duration=medium&filter_duration=long

I tried fixing that by adding a condition like

$j('.showCategory li a').each(function() {
    if(this.href.indexOf('filter_category') == -1) {
        var catId = $j(this).attr("data-id");
        this.href += (/\?/.test(this.href) ? '&' : '?') + 'filter_category='+ catId;
    } else {
        ????
    }
});

But in that case, it's not adding any parameter, but it's not replacing the value. How can I solve this please?

1 Answer 1

2

Use this pattern to do an in-place replacement with a regular expression:

} else {
this.href = this.href.replace(/filter_duration=(.+?)(&|$.*)()/, "filter_duration=" + catId + "$2"
}

This uses capture groups to find an existing filter_duration element query parameter, and replaces the existing value in place with a new value (in this case catId). This should work regardless of whether it is the last query parameter in the string or not.

That said, I wouldn't regard this solution as optimal, and you would probably be better off with storing the values that you want in your url in a client side javascript object, and then rebuild the url each time from scratch whenever anyone changes a category. That way you won't have to worry about difficult to test cases where something goes wrong with a replacement and the client getting into a bad state.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.