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,459
  • 3
  • 18
  • 33

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
  • 18,117
  • 1
  • 34
  • 54