Javascript 如何使 lodash _.replace 所有出现在字符串中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36429732/
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
How make lodash _.replace all occurrence in a string?
提问by Anthony
How to replace each occurrence of a string pattern in a string by another string?
如何用另一个字符串替换字符串中每次出现的字符串模式?
var text = "azertyazerty";
_.replace(text,"az","qu")
return quertyazerty
返回 quertyazerty
回答by mrstebo
You can also do
你也可以这样做
var text = "azertyazerty";
var result = _.replace(text, /az/g, "qu");
回答by Anthony
you have to use the RegExp with global option offered by lodash.
你必须使用 lodash 提供的带有全局选项的 RegExp。
so just use
所以只需使用
var text = "azertyazerty";
_.replace(text,new RegExp("az","g"),"qu")
to return quertyquerty
返回 quertyquerty
回答by Simon Hutchison
I love lodash, but this is probably one of the few things that is easier without it.
我喜欢 lodash,但这可能是少数没有它更容易的事情之一。
var str = str.split(searchStr).join(replaceStr)
As a utility function with some error checking:
作为带有一些错误检查的实用函数:
var replaceAll = function (str, search, replacement) {
var newStr = ''
if (_.isString(str)) { // maybe add a lodash test? Will not handle numbers now.
newStr = str.split(search).join(replacement)
}
return newStr
}
For completeness, if you do really really want to use lodash, then to actually replace the text, assign the result to the variable.
为了完整起见,如果您真的真的想使用 lodash,那么要实际替换文本,请将结果分配给变量。
var text = 'find me find me find me'
text = _.replace(text,new RegExp('find','g'),'replace')
References: How to replace all occurrences of a string in JavaScript?