Sercan Samet Savran
Sercan Samet Savran

Reputation: 947

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.

Upvotes: 1

Views: 326

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626774

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>

Upvotes: 2

Related Questions