简体   繁体   English

如何使 lodash _.replace 所有出现在字符串中?

[英]How make lodash _.replace all occurrence in a string?

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

You can also do你也可以这样做

var text = "azertyazerty";
var result = _.replace(text, /az/g, "qu");

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

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?参考资料: 如何替换 JavaScript 中所有出现的字符串?

Vanilla JS is fully capable of doing what you need without the help of lodash. Vanilla JS 完全有能力在没有 lodash 帮助的情况下做你需要的事情。

const text = "azertyazerty"
text.replace(new RegExp("az", "g"), "qu")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM