0

I want to replace all instances of 'foo' with 'foo2' using jQuery.

I've come across the following answer in other threads:

$("p").text(function(index, text) {
        return text.replace('foo', 'foo2');
});

But that only changes the first instance of foo in any given paragraph:

Fiddle: https://jsfiddle.net/sj76uh5r/

Dan382
  • 976
  • 6
  • 22
  • 44
  • check t his https://jsfiddle.net/sj76uh5r/1/ – guradio Apr 07 '16 at 09:50
  • Possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – apokryfos Apr 07 '16 at 09:54

1 Answers1

3

As stated in reference for .replace() here:

If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier (see "More Examples" below).

You need to use regeular expression with g flag set to replace all occurrences:

$("p").text(function(index, text) {
 return text.replace(/foo/g, 'foo2');
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • Thanks for that. If anyone reading this wants the example for multiple words it would look like this: https://jsfiddle.net/oL6y7080/1/ – Dan382 Apr 07 '16 at 10:08