JavaScript : replaceAll() function implementation

In a JavaScript there is no predefined function to replace all the occurrences of a String in a give text.

eg: 
 originalString = "Test abc test test abc test test test abc test test abc ";  
 changeString = originalString.replace('abc', '');  
 changeString--> Test test test abc test test test abc test test abc  

Only the first occurrence of 'abc' is replaced.

By using the following solution we can overcome the above constraint.
 var find = 'abc';  
 var originalString = new RegExp(find, 'g');  
 changeString = originalString .replace(re, '');  


Wrapped into a function
 function replaceAll(find, replace, str) {  
  return str.replace(new RegExp(find, 'g'), replace);  
 }  


Additional Info:
Here what happens is we are enabling the global property of our regular expression, so we can go from replacing one match at a time to replacing all matches at once.To enable the global property, just put a "g" at the end of the regular expression.

Comments