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

245
Views
Is there a regex to replace all occurences except for the first one?

I already tried to use this for above mentioned intention

var str = "48abc5,2d25.,ft87";
str = str.replace(/[^\d(,.)?]/g, '');
console.log(str);

I expected the output would be 485,225 because of the 0-1 condition through the question mark.

However my output is 485,225.,87

Simply my final approach is to have a number seperated by comma or a dot. Following pattern would fit my intention:

{1-9}+{0-9)?{, | . }{1-9}*

Would love to hear your solutions.

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

0

Inside character classes, all chars are literal, except for ^, \, [ and -. So, you cannot add ? there and expect it to behave as a quantifier.

You need

var str = "48abc5,2d25.,ft87";
str = str.replace(/[^\d,.]+/g, '').replace(/^([^.,]*(?:[.,][^.,]*)?).*/, '$1').replace(/^0+/, "");
console.log(str);

The .replace(/[^\d,.]+/g, '') part removes all chars other than digits, dots and commas.

The .replace(/^([^.,]*(?:[.,][^.,]*)?).*/, '$1') part keeps the first steak of digits and optionally a second streak of digits after the first . or ,.

The .replace(/^0+/, "") part removes one or more 0 digits at the beginning of the string.

Your fixed demo fiddle:

function testRegex(event){
    let evt = event || window.event
  console.log(evt.target.value)
  document.getElementById("result").innerHTML = "Result: "+ 
  evt.target.value.replace(/[^\d,.]+/g, '')
                            .replace(/^([^.,]*(?:[.,][^.,]*)?).*/, '$1')
                              .replace(/^0+/, "");
}
<label>Value:</label>
<input onkeyup="testRegex()" type="text"/>
<p id="result">Result:</p>

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!