[英]replace all comma seperated numbers to dot seperated numbers in string in javascript
假设有带数字的字符串,例如, test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text
我需要用逗号替换数字,用点替换相同的数字,并且不要更改其他任何内容。 所以字符串会变成
test() test 12.01% test (12.4) 12.3 s 2 some other text, other text, 2,text
我尝试过这样的事情:
var newstr = str.replace(/^\d+,\d+$/g, "\1.\2");
或var newstr = str.replace(^ \\ d * \\,?\\ d + $ / g,“ \\ 1. \\ 2”);
您可以这样操作并捕获2个组:
说明
(\\d+)
,
(\\d+)
var str = "test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text"; var newstr = str.replace(/(\\d+),(\\d+)/g, "$1.$2", "."); console.log(newstr);
yourString.replace(/(\d),(\d)/g, "$1.$2")
这将匹配数字之间的每个逗号。
尝试这个:
var newstr = str.replace( /\b(\d+),(\d+)\b/g, "$1.$2");
设置\\b
单词边界的目的是确保您不会意外匹配与字母相邻的数字。 由于示例的一部分包含文本2,text
,因此似乎可能会出现一些异常文本,例如2,1text
,在这种情况下,您可能不打算用逗号替换逗号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.