You can build a regexp matching any part of your string like this:
var urlPart = "wall_treatment";
var reg = new RegExp("([&?]+)" + urlPart + "=[^&]+");
Just replace "wall_treatment"
with any variable holding a string / part of your URL. [^&]+
matches anything up to the next occurence of &
in the url.
Replace it like this:
var yourURL = "?collection=French%20Curves&room=Bright%20And%20Airy&scene=best&wall_treatment=Wall Treatment 1";
var new_value = "Wall Treatment 2";
yourURL.replace(reg, "$1" + urlPart + "=" + new_value);
Having solved that, let me advise that you should probably try to build your url from an object or an array rather than replacing variables in the url string:
var myURLSearchObject = {},
addURLSearchPart = function(key, value) {
myURLSearchObject[key] = value;
},
buildURLSearch = function() {
var string = "?";
for (var key in myURLSearchObject) {
if (myURLSearchObject.hasOwnProperty(key)) {
string.length > 1 && (string += '&');
string += key;
string += '=';
string += myURLSearchObject[key];
}
}
return string;
};
Now you can use it like this:
addURLSearchPart('hello', 'hi');
addURLSearchPart('bye', 'goodbye');
buildURLSearch();