Reputation: 34884
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'));
}
}
Upvotes: 1
Views: 408
Reputation: 2960
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');
}
Upvotes: 0
Reputation: 387557
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'
Upvotes: 2