Reputation: 381
I am trying to replace each occurrence of a comma ',' but only if it is found in between two digits/numbers.
E.g. "Text, 10,10 text, 40 text, 10,60" should be returned as "Text, 1010 text, 40 text, 1060", where I replace the comma found between 10,10 and 10,60 but keep the commas after the text.
var text = "Text, 10,10 text, 40 text, 10,60";
var nocomma = text.replace(/,/g, '');
console.log(nocomma);
Upvotes: 4
Views: 1162
Reputation: 123
Your going to want match your digits and reference them in your replacement text using $n in the string where n is the index of your substring match. The following should work. You can see Mozilla for more information on replace and how it works.
let text = "Text, 10,10 text, 40 text, 10,60",
result = text.replace(/(\d),(\d)/g, '$1$2');
console.log(result);
Upvotes: 1
Reputation: 163207
If there can also be multiple occurrences of digits followed by a comma, you could use a single capturing group matching 1+ digits (\d+)
Then match a comma and use positive lookahead (?=
to assert what is directly to the right is a digit \d
.
In the replacement use the first capturing group $1
(\d+),(?=\d)
var text = "Text, 10,10 text, 40 text, 10,60 or 10,10,10";
var nocomma = text.replace(/(\d+),(?=\d)/g, '$1');
console.log(nocomma);
Upvotes: 1
Reputation: 37755
You can use capturing groups and replace
var text = "Text, 10,10 text, 40 text, 10,60";
var nocomma = text.replace(/(\d),(\d)/g, '$1$2');
console.log(nocomma);
If you're using modern browser which support both lookbehind you can use this too
str.replace(/(?<=\d),(?=\d)/g,'')
Upvotes: 6