【问题标题】:Regex replace with captured [duplicate]正则表达式替换为捕获的[重复]
【发布时间】:2017-08-23 22:12:30
【问题描述】:

我想将字符串中的所有非字母数字字符替换为“[”和“]”。

我试过了:

var text = "ab!@1b*. ef";
var regex = /\W/g;

var result  = text.replace(regex, "[$0]");

console.log(result);

我期待得到:

ab[!][@]1b[*][.][ ]ef

但是我得到了:

ab[$0][$0]1b[$0][$0][$0]ef

如何使用 Javascript(node) 做到这一点?

【问题讨论】:

  • 无需使用捕获组进行包装。使用text.replace(regex, "[$&]")

标签: javascript node.js regex regex-group


【解决方案1】:

您需要将组括在括号中以将其分配给 $1,如下所示:

var text = "ab!@1b*. ef";
var regex = /(\W)/g;

var result  = text.replace(regex, "[$1]");

console.log(result);

【讨论】:

    猜你喜欢
    • 2014-08-30
    • 2010-11-19
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2010-11-19
    • 2019-01-27
    相关资源
    最近更新 更多