【问题标题】:Replace comma if in between numbers with javascript如果在数字之间用 javascript 替换逗号
【发布时间】:2019-08-23 01:27:46
【问题描述】:

我正在尝试替换每次出现的逗号 ',',但前提是它位于两个数字/数字之间。

例如“Text, 10,10 text, 40 text, 10,60” 应返回为“Text, 1010 text, 40 text, 1060”,我替换 10,10 和 10,60,但在文本后保留逗号。

var text = "Text, 10,10 text, 40 text, 10,60";
var nocomma = text.replace(/,/g, '');
console.log(nocomma);

【问题讨论】:

    标签: javascript regex replace


    【解决方案1】:

    您可以使用捕获组和替换

    var text = "Text, 10,10 text, 40 text, 10,60";
    var nocomma = text.replace(/(\d),(\d)/g, '$1$2');
    
    console.log(nocomma);

    如果您使用的现代浏览器同时支持后视,您也可以使用它

    str.replace(/(?<=\d),(?=\d)/g,'')
    

    【讨论】:

    • 这样 (?
    【解决方案2】:

    如果还有多个数字后跟逗号,您可以使用单个捕获组匹配 1+ 数字 (\d+)

    然后匹配一个逗号并使用正向前瞻(?= 来断言直接在右边的是一个数字\d

    在替换中使用第一个捕获组$1

    (\d+),(?=\d)
    

    Regex demo

    var text = "Text, 10,10 text, 40 text, 10,60 or 10,10,10";
    var nocomma = text.replace(/(\d+),(?=\d)/g, '$1');
    console.log(nocomma);

    【讨论】:

      【解决方案3】:

      您想要匹配您的数字并在替换文本中使用 $n 在字符串中引用它们,其中 n 是您的子字符串匹配的索引。以下应该工作。 您可以查看Mozilla,了解有关替换及其工作原理的更多信息。

      let text = "Text, 10,10 text, 40 text, 10,60",
      	result = text.replace(/(\d),(\d)/g, '$1$2');
      	
      console.log(result);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-27
        • 2017-12-02
        • 2014-10-31
        • 1970-01-01
        • 2022-12-30
        • 2017-12-28
        • 2020-02-20
        相关资源
        最近更新 更多