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'));   
      }
    }
4
  • possible duplicate of Adding a parameter to the URL with JavaScript Commented May 17, 2015 at 14:31
  • @Bhullnatik, you better reread my question. Commented May 17, 2015 at 14:32
  • This appears to be a duplicate of stackoverflow.com/questions/10420955/…, though that question doesn't yet seem to have a terribly satisfactory answer. (You could of course try adding a bounty.) Commented May 17, 2015 at 17:17
  • @JoLiss, reread the question. Commented May 18, 2015 at 9:47

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

Comments

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');   
}

Comments

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.