用javascript替换双卷曲大括号

Mar*_*wan 3 javascript regex

我试图将String对象原型化为一个replaceWith函数,使我能够直接替换而不使用正则表达式

String.prototype.replaceWith = function(f, t) {
    var regExp = new RegExp("[" + f + "]", "g");
    return this.replace(regExp, t);
};
Run Code Online (Sandbox Code Playgroud)

当我在这个字符串{{Hello}}中测试我的代码时,我发现替换双花括号是个问题

测试

'{{Hello}}'.replaceWith('{{','<<').replaceWith('}}','>>');
Run Code Online (Sandbox Code Playgroud)

结果是

 "<<<<Hello>>>>"
Run Code Online (Sandbox Code Playgroud)

什么时候应该

"<<Hello>>"
Run Code Online (Sandbox Code Playgroud)

我的剧本出了什么问题?

谢谢你的帮助

Pau*_*aul 7

[{{]与正则表达式中[{]的完全相同{.方括号表示与该类中任何一个字符匹配的字符类.你应该改变:

"[" + f + "]"
Run Code Online (Sandbox Code Playgroud)

至:

f
Run Code Online (Sandbox Code Playgroud)

所以你有了:

String.prototype.replaceWith = function(f, t) {
    var regExp = new RegExp(f, "g");
    return this.replace(regExp, t);
};
Run Code Online (Sandbox Code Playgroud)

正如Marlin指出的那样具有相同的功能,String.prototype.replace除了你不需要添加g修饰符,并且在我看来'{{Hello}}'.replace(/{{/g, '<<');,其他编码器比其他编码器更简洁和易懂'{{Hello}}'.replaceWith('{{', '<<');.