Append Value To Url Search Param
I'm trying to add a value to a search parameter in an URL but it's partly not working. For example I've this URL: http://localhost.com/?color=Green&size=L How can I add now a
Solution 1:
Use a regular expression to match the color=...
parameter.
window.history.pushState(null, null, window.location.search.replace(/\bcolor=[^&]*/, '$&,Red'));
Solution 2:
You could parse the url, mutate it and build it up again:
functionparseURL(url) {
const [domain, rest] = url.split("?");
const args = {};
for(const [k, v] of rest.split("&").map(pair => pair.split("=")))
args[k] = v;
return { domain, args };
}
consttoURL = ({ url, args }) =>
url + "?" + Object.entries(args).map(pair => pair.join("=")).join("&");
const url = parseURL(window.location);
url.args["color"] += ",Red";
window.location = toURL(url);
That way you can easily modify all different parameters.
Post a Comment for "Append Value To Url Search Param"