In this second part of a two-part series on JavaScript String regular expressions, I look at multiline matching, how to replace matched sub-strings and how to split an available string using a regular expression object. Before we do that, let us look at the String way of extracting matches and then compare it with that of the RegExp object.
Replacing and Spliting JavaScript Sub Strings - Search and Replace a Matched sub-String (Page 3 of 4 )
After a match has occurred, you can replace the matched sub-string. That is, you look for the sub-string in the available string and replace it with what you really want. This aim is similar to that of the Find/Replace dialog box in text editors and word processors; the difference is that the content (available string) for the Find/Replace dialog box is usually very large (pages of text) and what the dialog box is finding does not have a pattern.
The RegExp object cannot do this. The String replace() method is used for this.
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)
or
var newAvailableString = availableString.replace(regexp, function)
I will give you detailed explanation of the first syntax. 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 replaced 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 a difference compared to the test and exec methods of the regexp object, in that you do not have to call it over and over to get all the possible matches with the global flag. You call the replace method once, with the global flag, and all possible matches will be replaced. I believe the RegExp object methods lack this characteristic.
The use of the second syntax is left as an exercise for you.