将所有逗号分隔的数字替换为javascript中的字符串中的分隔数字

时间:2018-01-15 19:55:52

标签: javascript regex

假设有数字的字符串,例如, 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”);

  • 我认为这应该与逗号匹配任何数字:^ \ d * \,?\ d + $

3 个答案:

答案 0 :(得分:3)

你可以这样做并捕获2组:

(\d+),(\d+)

<强>解释

  • 第1组:捕获1个或多个数字(\d+)
  • 匹配逗号,
  • 第2组:捕获1个或多个数字(\d+)

&#13;
&#13;
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;
&#13;
&#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,在这种情况下您可能打算用句点替换逗号。

相关问题