1

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 second value to color separated with a ,?

This is how the URL must look after setting a second param:

http://localhost.com/?color=Green,Red&size=L

I've tried it with this here:

window.history.pushState(null, null, window.location.search + ',' + 'Red');

But the result is:

http://localhost.com/?color=Green,Red&size=L,Red

So how can I add a value comma separated to a search parameter in my URL?

chazsolo
  • 6,692
  • 1
  • 15
  • 38
Mr. Jo
  • 3,961
  • 1
  • 22
  • 54
  • The result you say you're getting doesn't look right. It should only have `,Red` at the end, not in the middle. – Barmar Dec 07 '18 at 22:05
  • 2
    Possible duplicate of [How can I add or update a query string parameter?](https://stackoverflow.com/questions/5999118/how-can-i-add-or-update-a-query-string-parameter) – Heretic Monkey Dec 07 '18 at 22:07
  • 1
    @HereticMonkey no, it's not. – Mr. Jo Dec 07 '18 at 22:39

2 Answers2

3

Use a regular expression to match the color=... parameter.

window.history.pushState(null, null, window.location.search.replace(/\bcolor=[^&]*/, '$&,Red'));
Barmar
  • 596,455
  • 48
  • 393
  • 495
0

You could parse the url, mutate it and build it up again:

  function parseURL(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 };
 }

 const toURL = ({ 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.

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120