1

I want to update the url query string by clicking on checkbox. Here's the code, it doesn't work correctly

param1=param1=true
param1=param1=param1=false
param1=param1=param1=param1=true

instead of:

param1=false
param1=true

Here's an unrefactored code:

if (this.checked) {
      if (window.location.href.search('[?&]') === -1) {
        window.history.pushState('object or string', 'Title', window.location.href + '?param1=true');  
      } else {
        window.history.pushState('object or string', 'Title', window.location.href.replace(/param1=false|true/i, 'param1=true'));   
      }

    } else {
      if (window.location.href.search('[?&]') === -1) {
        window.history.pushState('object or string', 'Title', window.location.href + '?param1=false');  
      } else {
        window.history.pushState('object or string', 'Title', window.location.href.replace(/param1=false|true/i, 'param1=false'));   
      }
    }
アレックス
  • 24,309
  • 37
  • 129
  • 229
  • possible duplicate of [Adding a parameter to the URL with JavaScript](http://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript) – Bhullnatik May 17 '15 at 14:31
  • @Bhullnatik, you better reread my question. – アレックス May 17 '15 at 14:32
  • This appears to be a duplicate of http://stackoverflow.com/questions/10420955/history-pushstate-change-query-values, though that question doesn't yet seem to have a terribly satisfactory answer. (You could of course try adding a bounty.) – Jo Liss May 17 '15 at 17:17
  • @JoLiss, reread the question. – アレックス May 18 '15 at 09:47

2 Answers2

2

Consider this:

> 'param1=false'.replace(/param1=false|true/i, 'param1=true')
"param1=true"
> 'param1=true'.replace(/param1=false|true/i, 'param1=true')
"param1=param1=true"
> 'true'.replace(/param1=false|true/i, 'param1=true')
"param1=true"

The thing is that your regular expression is accepting either param1=false or just true. You need to put the false|true part in a group (in parentheses) to make the | not apply to the param1= part too. So your regular expression should be /param1=(false|true)/i:

> 'param1=true'.replace(/param1=(false|true)/i, 'param1=true')
'param1=true'
poke
  • 307,619
  • 61
  • 472
  • 533
0

If there are no other parameters in your query string, you could reconstruct your url like this:

var href = window.location.protocol + '//' + window.location.host + window.location.pathname;
if (this.checked) {
    window.history.pushState('object or string', 'Title', href + '?param1=true');  
} else {
    window.history.pushState('object or string', 'Title', href + '?param1=false');   
}
Renfei Song
  • 2,811
  • 2
  • 22
  • 29