1

I noticed that Javascript inbuilt replace function cannot replace more that one particular character at a go.

I have a String say var word = "sony sony sony is good"

but when i want to replace all sony with apple.

var res = word .replace("sony", "apple");

I notice it doesnt replace all sony, rather it replaces them one after the other.

How can I make javascript , change all instance of a string to another at once ?

Oto-obong Eshiett
  • 1,307
  • 1
  • 13
  • 30

1 Answers1

1

You can simply use the replace with regex with the g (for global parameter) to replace all:

var sentence = "sony sony sony is good"
console.log(sentence.replace(/sony/g, 'apple'))
Akrion
  • 17,012
  • 1
  • 30
  • 48