Replace All Occurrences of a String using Javascript
In the second method where we used regular expression, if we identify the regular expression as a global regular expression we can easily replace all occurrences of a string within an other string value in a given text using Javascript.
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.
var string_variable;
string_variable = "Replace text using javascript replace function within a javascript string variable";
string_variable = string_variable.replace(/javascript/g, "js");
alert(string_variable);
No comments:
Post a Comment