Javascript has a “replace” method which can be used to replace all occurances of a string. Consider for example that you want to replace all the occurances of the word “Miscellaneous” to “Amazing”.
var originalStr = 'This is a Miscellaneous Post. Miscellaneous posts will be put here.'; var newStr = originalStr.replace('Miscellaneous','Amazing'); alert(newStr);
If we run the above code then it will replace first occurance of “Miscellaneous” to “Amazing”. And it will return from there without modifying further occurances.
So to replace all occurances we should use regular expression. String.replace method of JavaScript allows us to specify regular expression as the first parameter.
Lets modify our existing code to use regular expression and replace all “Miscellaneous” to “Amazing”.
var originalStr = 'This is a Miscellaneous Post. Miscellaneous posts will be put here.'; var newStr = originalStr.replace(/Miscellaneous/gi,'Amazing'); alert(newStr);
Now above code will replace all occurances of a string in JavaScript.
We have added “g” identifier at the end of the regular expression to match it globally and perform replace operation. Even we have added “i” identifier, it will do “case insensitive” replacing, matching “Miscellaneous”, “miscellaneous” etc.