0

I am trying to do a js regex that will search for a parameter in an URL and if found replace it's value. If the parameter is not found, then it will be added to the URL.

Here is 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

My 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

I've managed to do the first one:

search for

/^(http[s]?:\/\/www\.domain)(.*)(paramZ\=[\d]+)(.*)$/g

replace with

$1$2paramZ=987654$4

Here is a working example: https://regex101.com/r/9Ui8vx/1

I don't know even if it's possible to acheive this in only one regex.

edysoft
  • 3
  • 2
  • Why not -> [How can I get query string values in JavaScript?](http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript) – adeneo Oct 04 '16 at 15:35
  • Or [add or update query string parameter](http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter). – Wiktor Stribiżew Oct 04 '16 at 15:42
  • This needs to go into a system that will only accept search and replace regex-s. Unfortunetly, no coding can be done. – edysoft Oct 04 '16 at 15:44
  • regular expressions are not an appropriate tool for accurately parsing query strings. – zzzzBov Oct 04 '16 at 15:56

1 Answers1

0
/(^https?:\/\/[^?#]*\?)((?!paramZ=)\w*=\w*;?)*?((paramZ=\w*;?)?)/gm

(skips any number of other parameters, selects required one or nothing)

Dimava
  • 7,654
  • 1
  • 9
  • 24