假设有数字的字符串,例如,
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”);
答案 0 :(得分:3)
你可以这样做并捕获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);
&#13;
答案 1 :(得分:1)
yourString.replace(/(\d),(\d)/g, "$1.$2")
这将匹配数字之间的每个逗号。
答案 2 :(得分:0)
试试这个:
var newstr = str.replace( /\b(\d+),(\d+)\b/g, "$1.$2");
在其中设置\b
字边界的目的是确保您不会意外地匹配与字母相邻的数字。由于您的示例的部分内容包含2,text
文字,因此可能会显示某些不寻常的文字,例如2,1text
,在这种情况下您可能不打算用句点替换逗号。