How to replace all occurrences of string in javascript.


Back to learning
Created: 16/04/2015


How to replace all occurrences of string in javascript.


I need to replace some text in string in javascript but it only replace the first occurrence, whats the problem?

Example: 'text'.replace('t', '9');     -> result: "9ext"

Answer: The String.replace() method will only replace the first occurence to replace all the occurrences you may use simple regular expresion like this:

   'text'.replace(/t/g, '9');   -> result: "9ex9"

:: g is for globaly

Summarizing

s1 = 'text'.replace('t','9')   // result: '9ext' (only the first 't' replaced)
s2 = 'text'.replace(/t/g,'9')  // result: '9ex9' (all occurrences of 't' replaced)