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 - Extracting Continued (Page 2 of 4 )
Everything being equal, the regexp or string methods match the first occurrence in the available string. If you want to match more than one element in the available string, you have to use the global flag.
This is logical. In the case of the String match() method, the returned array will have all the elements that are matched when you use the global flag.
Consider the regexp,
re = /[crb]at/;
Consider the available string,
"A cat is an animal. A rat is an animal. A bat is an animal."
The pattern should match "cat," "rat" and "bat" in the available string. With these variables, the following code displays a three-element array, with the values "cat," "rat" and "bat:"
<html>
<head>
</head>
<body>
<script type="text/javascript">
var availableString = "A cat is an animal. A rat is an animal. A bat is an animal.";
var re = /[crb]at/g;
myArray = availableString.match(re);
alert(myArray);
</script>
</body>
</html>
With the global flag, the return array returns all three sub-strings found.
Comparison
We can compare the way the RexExp exec() method handles the returned array with the way the String match() method handles the returned array. With the exec() method, you have to call the exec() function over and over, making use of the lastIndex property. With the match() method, you do not need to call the match() function over and over (you do not need the help of any property). The code is not straightforward with the exec() method. The code is straightforward with the match() method.
Multiline Matching
In a text editor the text is written in lines, one below the other. You may want to look for sub-strings in these lines by matching. Unfortunately, the specification is not clear on multiline matching, both for the RegExp object and the String regular expression methods.
I have consulted other sources that talk about regular expressions in JavaScript. These sources do not really say anything about multiline matching, both for the RegExp object and the String regular expression methods. So I will not say any more on this. The only advice I can give you is that when you have an available string that is made up of lines of text, try your best with the global flag, preferably with the String regular expression methods.