在javascript/nodejs中搜索并替换所有内容

Yal*_*ber 2 javascript regex node.js

我的替换所有功能如下,它是commonHelper.js文件

exports.replaceAll = function (find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}
Run Code Online (Sandbox Code Playgroud)

然后我做了以下

var commonHelper = require('./commonHelper');
var html_body = commonHelper.replaceAll('[[username]]', user_row.username, template_row.message_body);
html_body = commonHelper.replaceAll('[[forgot_pass_link]]', forgot_pass_link, html_body);
Run Code Online (Sandbox Code Playgroud)

这不能正确替换[[key]]部件.我该怎么改变来解决这个问题?

Yal*_*ber 6

我不得不替换特殊字符.我更新了替换所有功能

exports.replaceAll = function (find, replace, str) {
  var find = find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  return str.replace(new RegExp(find, 'g'), replace);
}
Run Code Online (Sandbox Code Playgroud)