Reputation: 1089
I have a script that adds a parameter to the url on a click - and replaces the the parameter with another on the second click. This works great.
However there is a scenario when there already is a parameter in place - and I then need this click to replace that value.
Example:
Click one gives
?param=largegrid
Second one replaces the value and gives
?param=smallgrid
But sometimes the url looks like this:
?param=grid or param=grid&fss=tablet
in this case i want the click to replace the first value so the url looks like
?param=large or param=largegrid&fss=tablet
and the same for the second click.
$('.click10').on('click', function() {
console.log("Clicked");
var url = window.location.pathname;
var url = window.location.href;
if (url.indexOf('?param=largegrid') > -1) {
url = url.replace("?param=largegrid", "") + '?param=smallgrid'
} else {
url = url.replace("?param=smallgrid", "") + '?param=largegrid'
}
window.location.href = url;
});
Upvotes: 0
Views: 89
Reputation: 18647
You can try this, search for the param of either grid or large-grid and next you can replace them alternatively.
if (url.indexOf('?param=grid') > -1) {
url = url.replace("grid", "") + 'largegrid'
} else if(url.indexOf('largegrid') > -1) {
url = url.replace("largegrid", "") + 'smallgrid'
} else if(url.indexOf('smallgrid') > -1) {
url = url.replace("smallgrid", "") + 'largegrid'
}
Upvotes: 1
Reputation: 38400
I can recommend to library URI.js. It helps parsing and building URIs/URLs. For example, you don't need to worry if the query parameter already exists:
For example, both
var newURL = URI("http://www.example.com/").setQuery("param", "smallgrid").toString();
and
var newURL = URI("http://www.example.com/?param=largegrid").setQuery("param", "smallgrid").toString();
both result in http://www.example.com/?param=smallgrid
An example for your event handler using a callback:
$('.click10').on('click', function() {
var url = window.location.href;
url = URI(url).search(function(queryData) {
queryData.param = (queryData.param === "largegrid") ? "smallgrid" : "largegrid";
});
window.location.href = url;
});
Upvotes: 0
Reputation: 15923
You can use the regex for that like
url= url.replace(/(largegrid=)[^\&]+/,updated_largegrid);
Okay what you can do is(as per your posted code) :
var url = window.location.href;
url= url.replace(/(largegrid=)[^\&]+/,updated_largegrid);
Upvotes: 0