在 javascript/nodejs 中搜索和替换所有内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18307772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Search and replace all in javascript/nodejs
提问by Yalamber
My replace all function is as below, it is in commonHelper.js file
我的替换所有功能如下,它在 commonHelper.js 文件中
exports.replaceAll = function (find, replace, str) {
return str.replace(new RegExp(find, 'g'), replace);
}
Then I do following
然后我做以下
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);
this is not properly replacing the [[key]] parts here. What should I change to fix this?
这不能正确替换此处的 [[key]] 部分。我应该改变什么来解决这个问题?
回答by Yalamber
I had to replace special characters. My updated replace all function
我不得不替换特殊字符。我更新的替换所有功能
exports.replaceAll = function (find, replace, str) {
var find = find.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&');
return str.replace(new RegExp(find, 'g'), replace);
}
回答by Grant Li
There is a replaceAll command in string module.
string 模块中有一个 replaceAll 命令。
You might be able to use it like this in util.js:
你可以在 util.js 中像这样使用它:
var S=require('string');
exports.replaceAll=function(hay,rplfrom,rplto)
{
return S(hay).replaceAll(rplfrom,rplto).s;
};
回答by Martlark
You can use split and join as a replace all. This removes any issues with regex special characters messing up the find and replace. Example:
您可以使用 split 和 join 作为全部替换。这消除了正则表达式特殊字符搞乱查找和替换的任何问题。例子:
>> "[boo].blah.[boo].blah".split("[boo]").join("(scare)")
"(scare).blah.(scare).blah"