简体   繁体   中英

Regex to replace character in Javascript

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 exemples:

0,23433,222

Should return

0.23433222

Or

123,33

Should return

123.33

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);

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);

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM