1

I was wondering how I'd go about replacing multiple same words with another string.

ex.

"abc I abc was abc going abc to abc bed."

to

"* I * was * going * to * bed."

(which is an example where 'abc' would be changed to '*')

I tried replace("abc", "*"); but I've noticed this only changes the first abc token that appears in the string and leaves all the others intact.

Any ideas?

dk123
  • 18,684
  • 20
  • 70
  • 77

6 Answers6

3

Use flag "g":

string.replace(/abc/g, '*')
Vitaly
  • 611
  • 1
  • 7
  • 21
3

You want to perform a global replacement within a string.

To do so, in JavaScript, you need to:

  1. Pass a Regular Expression (RegEx) as the search value (the first argument) to the replace method
  2. Turn on the global modifier so that the RegEx is searched globally through your search string.

For your requirement:

var str= "abc I abc was abc going abc to abc bed.";
var newStr = str.replace(/abc/g, "*"); //newStr = "* I * was * going * to * bed."
Darkhogg
  • 13,707
  • 4
  • 22
  • 24
B.D.
  • 108
  • 1
  • 7
  • Thanks for the answer. I chose this as the answer as I didn't even know what a regular expression was and the added explanation helps a lot. – dk123 Nov 14 '13 at 08:22
1

You need the /g modifier: str.replace(/abc/g, "*")

elixenide
  • 44,308
  • 16
  • 74
  • 100
1

Try this :

var myString = "abc I abc was abc going abc to abc bed.";

var modifiedString = "";

modifiedString = myString.replace(/abc/g, '*');

alert(modifiedString);

Also try to this:

myString .replace(new RegExp("abc","g"),"*"));

Try This

Ishan Jain
  • 8,063
  • 9
  • 48
  • 75
1
var str= "abc I abc was abc going abc to abc bed.";

str = str.replace(/abc/g,"*");
Ankit Tyagi
  • 2,381
  • 10
  • 19
1

You need to use RegExp as followed:

    var str = "abc I abc was abc going abc to abc bed.";
    console.log(str.replace(/abc/g, "*"));

have a try.

Ardy
  • 161
  • 3