1

I'm looking to remove a parameter from a URL with a click event. The issue is that the parameter can either have an & before it or not. So the form is either search=MYSEARCHTERM or &search=MYSEARCHTERM.

I have the following which appears to work fine for one or other but not both. I was thinking that I could have an if / else statement one of which contains something like this. (Excuse the crappy regex but I've never written it before)

var searchKeywordRegx = new RegExp(/(?:&)/ + 'search=' + searchKeyword);

$('.searchKeyword').click(function() {
    $(this).remove();
    var searchKeywordRegx = new RegExp('search=' + searchKeyword);
    console.log(searchKeywordRegx);
    document.location.href = String( document.location.href ).replace(searchKeywordRegx , "" );
});

Am I way off base here?

2 Answers 2

2

Use ? to make something optional in a regexp:

var searchKeywordRegx = new RegExp('&?search=' + searchKeyword);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah! so simple. Thanks
1

Seems you can do this without regular expressions. If you simply remove that portion of the document location's "search":

document.location.search = document.location.search
    .replace('search=' + encodeURI(searchKeyword), '');

3 Comments

I'm heard of encodeURI but I'm not familiar with it. I'll have to check it out. Thanks.
@LMG, I'm using encodeURI because it will ensure that the values have proper encoded strings. For example, if the string was search=testing this (with the space), then what is in the URL is search=testing%20this. So encodeURI makes sure that the value you pass to it will match how it would look in a URL.
Thanks for the clarification.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.