0

Let's say I have a URL like:

www.domain.com/index.jsp?queryParam1=true&queryParam2=false&queryParam3=12

How would I remove just queryParam2=false from the string on page reload?

I took a look at this but it seems to remove all the query parameters. I am in particular trying to do this when a user presses the "Reload this page" button on their browser or they are using the associated hotkey.

Community
  • 1
  • 1
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80

3 Answers3

0
location = location.href.replace(/(\?|\&)(queryParam2=)([^&]*)/, '$1');
Shadi Shaaban
  • 1,670
  • 1
  • 10
  • 17
  • True, but you don't want to omit the ? or & check so not to match with other query strings like: (page?otherqueryParam2=foo&var=foo2) and (page?foo=queryParam2&var=foo2) ..etc – Shadi Shaaban May 25 '16 at 19:28
  • Ahh, good point. I'd use `\b` to check for a word boundary, but that works also. – 4castle May 25 '16 at 19:31
0

Use the regex \bqueryParam2=false&? to locate the query parameter, and optionally a trailing & if there are more parameters beyond it. If you want to remove queryParam2 no matter what value it has, use the regex \bqueryParam2[^&]*&?.

redirectButton.onclick = function() {
    window.location.href = window.location.href.replace(/\bqueryParam2=false&?/,"");
}

var url = "www.domain.com/index.jsp?queryParam1=true&queryParam2=false&queryParam3=12";
url = url.replace(/\bqueryParam2=false&?/,"");
document.body.innerHTML = url;
4castle
  • 32,613
  • 11
  • 69
  • 106
0

Here is a snippet that would remove queryParam2 from a string:

var url = "www.domain.com/index.jsp?queryParam1=true&queryParam2=false&queryParam3=12"

url.replace(/\queryParam2=(.*)&/, '');

// Produces:
// "www.domain.com/index.jsp?queryParam1=true&queryParam3=12"
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54
  • This doesn't work if there's more than one `&` after `queryParam2` because `.*` will be greedy. You could use `.*?` or even better: `[^&]*`. – 4castle May 25 '16 at 19:23