41

How to replace each occurrence of a string pattern in a string by another string?

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

return quertyazerty

Cœur
  • 37,241
  • 25
  • 195
  • 267
Anthony
  • 3,989
  • 2
  • 30
  • 52

4 Answers4

51

You can also do

var text = "azertyazerty";
var result = _.replace(text, /az/g, "qu");
mrstebo
  • 911
  • 9
  • 12
  • 5
    This is essentially a code-only answer, which is not as useful as answers that offer some description. You might mention that this is a "simpler" way to write a regular expression, but that you are in fact using a regular expression. – random_user_name Apr 24 '18 at 18:57
47

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

Anthony
  • 3,989
  • 2
  • 30
  • 52
  • 3
    The "g" modifier is used to perform a global match (find all matches rather than stopping after the first match) – Sergey_T Jan 15 '19 at 16:18
27

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?

Simon Hutchison
  • 2,949
  • 1
  • 33
  • 32
8

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")
Dave Kalu
  • 1,520
  • 3
  • 19
  • 38