How to replace each occurrence of a string pattern in a string by another string?
var text = "azertyazerty";
_.replace(text,"az","qu")
return quertyazerty
How to replace each occurrence of a string pattern in a string by another string?
var text = "azertyazerty";
_.replace(text,"az","qu")
return 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.
so just use
var text = "azertyazerty";
_.replace(text,new RegExp("az","g"),"qu")
to return quertyquerty
I love lodash, but this is probably one of the few things that is easier without it.
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.
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?
Vanilla JS is fully capable of doing what you need without the help of lodash.
const text = "azertyazerty"
text.replace(new RegExp("az", "g"), "qu")