Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace comma if in between numbers with javascript

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);
like image 745
Joe Berg Avatar asked Sep 16 '25 15:09

Joe Berg


1 Answers

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,'')
like image 109
Code Maniac Avatar answered Sep 18 '25 04:09

Code Maniac