【问题标题】:RegExp replace do not replaces with pattern正则表达式替换不替换为模式
【发布时间】:2016-07-17 23:26:33
【问题描述】:

我想将 #### 替换为 ##-##(# := 任何数字符号)。

if (/^([0-9]{2})([0-9]{2})$/.test(str)) {       
    str = str.replace("/^([0-9]{2})([0-9]{2})$/", "$1-$2");
    console.log(str);
}

在控制台中我得到####(不是##-##)。
我做错了什么?

【问题讨论】:

    标签: javascript regex replace pattern-matching regexp-replace


    【解决方案1】:

    您需要将正则表达式传递给替换函数而不是字符串 - 在您的情况下,您正在尝试替换字符串文字 /^([0-9]{2})([0-9]{2})$/

    str = str.replace(/^([0-9]{2})([0-9]{2})$/, "$1-$2");
    

    var str = '4455';
    snippet.log('before: ' + str);
    str = str.replace(/^([0-9]{2})([0-9]{2})$/, "$1-$2");
    snippet.log('after: ' + str);
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      相关资源
      最近更新 更多