Trying to create a JavaScript regex that searches for a parameter in a URL and replaces its value if found. If the parameter is not found, it should be added to the URL.
Here are a couple of scenarios:
http://www.domain.com/?paramZ=123456
https://www.domain.com/?param1=val1;param2=val2;param3=val3;paramZ=123456
http://www.domain.com/one/or/more?paramZ=123456;param1=val1;param2=val2;param3=val3
https://www.domain.com/one/or/more?param1=val1;paramZ=123456;param2=val2;param3=val3
http://www.domain.com/one/or/more?param1=val1;param2=val2;param3=val3
The goal is to do the following:
- Find paramZ=XXXXXX and replace it with paramZ=YYYYYY
- If paramZ does not exist, add it with the value YYYYYY
Managed to achieve the first one:
Search for:
/^(http[s]?:\/\/www\.domain)(.*)(paramZ\=[\d]+)(.*)$/g
Replace with:
$1$2paramZ=987654$4
Working example: https://regex101.com/r/9Ui8vx/1
Not sure if it's possible to accomplish this with just one regex.