Wednesday, February 16, 2011

How to Replace All Occurrences of a String using Javascript Replace Function

As we all use javascript's "replace()" function to replace string but normally it replace only first matched text and leave all other.
for eg.
var string_variable = "this is stringToBeReplaced and now again stringToBeReplaced occurred";
string_variable = string_variable.replace("stringToBeReplaced", "NewString");
now if you will print value of string_variable then it will be like:
"this is NewString and now again stringToBeReplaced occurred"
so as you can see in above string only first concurrence of "stringToBeReplaced" is replaced.

Now, if you wants to replace all occurrence of string then the same "replace()" function can help you out:

eg.
var string_variable = "this is stringToBeReplaced and now again stringToBeReplaced occurred";
string_variable = string_variable.replace(/stringToBeReplaced/g, "NewString");
now if you will print value of string_variable then it will be like:
"this is NewString and now again NewString occurred"
How we can enable global regular expression is as simple as adding the "g" identifier following the regular expression.
Using "g" following the regular expression pattern, builtin javascript replace method will replace all matches and all occurences of the given text variable with the new string.

Solution By: Rajesh Rolen

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates