regex replace up to char or end of line

Hello,  i had this strings¶m2=value2¶m2=value2¶m3=value3

I want replace, param2=xxxx with param2=bbbb
but i'm having problems to detect the end to group to replace, due can be & or end of line
I tryed this mystring.replace(/&param2=(.*)(?=&|$)/gi,'&param2=newvalue' ) but don't work
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.


The % in the pattern match deals with URLencoded I.e.%20 as a space.
Carl BohmanCommented:
Rather than using a character class that explicitly includes characters (which may exclude valid characters, such as can be included in international URLs), it may be best to use an inverted character class like this:
mystring.replace(/param2=[^&]*(?=&|$)/g, 'param2=newvalue'); 

Open in new window

Also note that you want to be sure to not capture the following "&" (if there is one) when you do the replace or it will be removed by the replacement text.  To deal with that, I'm using a lookahead (which doesn't capture and isn't included in the matched string that gets replaced).
käµfm³d 👽Commented:
You really shouldn't need more than:


Open in new window your pattern. Within a URL, ampersand is the delimiter between two key/value pairs, so just match everything that isn't an ampersand. There is no need to check for end-of-line/string.

I would change the leading ampersand to an alternation, though. Unless you can guarantee that "param2" will always not be the first key/value pair, then it's possible that a ? preceeds it:


mystring.replace(/(\?|&)param2=[^&]*/gi, '$1param2=newvalue')

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Regular Expressions

From novice to tech pro — start learning today.