Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
How to replace query parameter only if it exists using string replace All regex

I have following urls :

https://test1.com/path?query1=value1

and

https://test2.com/path

I am trying to add additional query param to all urls, so i am trying something like

url.replaceAll(/(.*)[?]?(.*)/g,"$1?newquery=newvalue&$2")

let url = "https://test1.com/path?query1=value1"
console.log(url.replaceAll(/^(.*)[?]?(.*)$/g,"$1?newquery=newvalue&$2"))
url = "https://test1.com/path"
console.log(url.replaceAll(/^(.*)[?]?(.*)$/g,"$1?newquery=newvalue&$2"))

But it doesnt work as expected , could someone shed some light

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

First let's go through what your regex is doing, then we can fix it. Your regex:

^ - the beginning of the string
(.*) - match any character 0 or more times - as many times as possible (greedy)
[?]? - match `?` 0 or 1 times
(.*) - match any character 0 or more times - as many times as possible (greedy)
$ - the end of the string

Really the main problem here is that the first capturing group captures as many times as possible, so that'll always match the entire url. We can make that non-greedy by using .*?, so we end up with ^(.*?)[?]?(.*)$. However now we end up with the problem that the last capturing group captures the entire url - we could make this non-greedy but then it wouldn't match any characters at all. Instead, we should make sure that this group will only capture when ? is present, so we can make [?]? non-optional, move it into the next capturing group, and make the last group optional, like this: ([?](.*))?. Whilst we're at it, we might as well use \? instead of [?] and we end up with ^(.*?)(\?(.*))?$. This works, as the $ signifies that we want to capture right up to the end. With this we'd need to use $3 instead of $2 as $2 now contains ? as well when replacing, so we can use a non-capturing group to eliminate that problem. So our final regex is /(.*?)(?:\?(.*))?/g.

Your final code will look like this:

let url = "https://test1.com/path?query1=value1"
console.log(url.replaceAll(/^(.*?)(?:\?(.*))?$/g,"$1?newquery=newvalue&$2"))
url = "https://test1.com/path"
console.log(url.replaceAll(/^(.*?)(?:\?(.*))?$/g,"$1?newquery=newvalue&$2"))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!