String Objects and Regular Expressions in JavaScript
Welcome to the fifth article in a five-part series on JavaScript regular expressions. In this article, we begin the second and final phase of the series. In this phase we shall deal more with the properties and methods of the regexp object. We shall also deal with some properties and methods of the string object that are related to regular expressions.
String Objects and Regular Expressions in JavaScript - Search and Replace (Page 4 of 5 )
You can search (match) a sub-string in an available string, and then replace it with a new sub-string. The syntax is
var newAvailableString = availableString.replace(regexp, newSubStr)
The method replace() is a method of the string object (availableString). It is not a method of the regular expression object. Regexp, above, is either the variable name of the regular expression object or the literal.
After the substitution, the original available string is not changed. The string returned is the available string with the substituted sub-string. The following script illustrates this.
<script type = "text/javascript">
var availableString = "This is a girl";
var re = /girl/;
var newSubStr = "boy";
var newAvailableString = availableString.replace(re, newSubStr);
alert(availableString);
alert(newAvailableString);
</script>
Try the above code.
To replace all possible matches, include the g flag in the regexp. The following script illustrates this:
<script type = "text/javascript">
var availableString = "This is a girl. That is a girl.";
var re = /girl/g;
var newSubStr = "boy";
var newAvailableString = availableString.replace(re, newSubStr);
alert(availableString);
alert(newAvailableString);
</script>
The replace method of the string object has an advantage over the test and exec methods of the regexp object, in that you do not have to call it over and over to get all of the possible matches with the global flag. You call the replace method once with the global flag, and all possible matches will be replaced.