I'm trying to create a regex to replace comma by a dot and only have one dot and delete all of the other ones, for example:
0,23433,222
Should return
0.23433222
Or
123,33
Should return
123.33
CodePudding user response:
You can first replace the first comma with a dot and then remove the rest of the commas
let str = '0,23433,222';
str = str.replace(/,/, '.').replace(/,/g, '');
console.log(str);
CodePudding user response:
Just replace the first comma with a point and then remove all remaining commas. No regular expressions needed:
const str = "0,23433,222";
const res = str.replace(",", ".").replaceAll(",", "");
console.log(res);
CodePudding user response:
You can store the number of replaced commas in a variable, check whether it is 0
and increment it inside the replace
callback:
let str = "0,23433,222", i = 0;
const res = str.replace(/,/g, c => !i ? '.' : '')
console.log(res)