简体   繁体   English

正则表达式替换 Javascript 中的字符

[英]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可以先把第一个逗号换成点然后去掉逗号的rest

 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:您可以将替换逗号的数量存储在一个变量中,检查它是否为0并在replace回调中递增它:

 let str = "0,23433,222", i = 0; const res = str.replace(/,/g, c =>?i++. ':'. '') console.log(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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