Reputation: 5198
I have an address like this:
117042,ABC DEF,HIJ KLMNOP,9,170
and want to have
117042,ABC DEF,HIJ KLMNOP 9 170
I tried it with this replace Regex
address = address.replace(/,[\d]/g, " ");
but this results in
117042,ABC DEF,HIJ KLMNOP 70
I do not want to replace the digit but still need to check if the digit comes after the comma to not match the other commas.
I am not very good with regex thats why I am asking for help.
Upvotes: 2
Views: 172
Reputation: 627087
You may only replace commas after numbers if they occur at the end of string:
var s = "117042,ABC DEF,HIJ KLMNOP,9,170";
var res = s.replace(/,(\d+)(?=(?:,\d+)*$)/g, " $1");
console.log(res);
The ,(\d+)(?=(?:,\d+)*$)
regex matches:
,
- a comma(\d+)
- (Group 1, referred to via $1
from the replacement pattern) one or more digits(?=(?:,\d+)*$)
- a positive lookahead that requires 0+ sequences of ,
+ one or more digits at the end of the string.Upvotes: 3