Trying to use Javascript regex to grab a section of “&” delimited text whether or not it's the last value

My text looks similar to this:

action=addItem&siteId=4&lang_locale=en_US&country=US&catalogId=1&productId=417689&displaySize=7&skuSize=2194171&qty=1&pil=7&psh=had+AIRJRnjbp7+rGivIKg00

and I want to replace the value of 'psh'. It may sometimes not be the last value (it may be followed by &something=else).

I've tried doing these lines of code:

  1. var text = text.replace(/&psh=.*(?=&|$)/, "&psh=" + data.psh);
  2. var text = text.replace(/&psh=.*(?=[&|$]+)/, "&psh=" + data.psh);
  3. var text = text.replace(/(?:&psh=)(.*)(?=[&|$]+)/, data.psh);

None of them work for both situations. Use this site to check regexes.

Answers


This should work:

var text = text.replace(/&psh=[^&]*/, "&psh=" + data.psh);

[^&]* matches a string of any length that consists of any characters except &, therefore the match will continue until the end of the string or until (but not including) the next &, whichever comes first.


Need Your Help

How to serve a file with JSP?

java jsp java-ee binary-data

This may sound totally stupid, but is a case of real life :(

AVL Tree implementation with nodes or without nodes

c++ nodes avl-tree

We have a class project to implement an AVL tree.