Replacing and Spliting JavaScript Sub Strings
(Page 1 of 4 )
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.
Extracting matches with the String match() method.
Note: The JavaScript String object has the match() method; it is not the RegExp object that has the method. This method returns an array of one element (the first) if it sees a match. If you use a global flag, then the elements in the array will be all the sub-strings found. The way the String match() method is used is straightforward. There is no ambiguity, as we shall see below.
Consider the regexp,
re = /rat/;
Consider the available string,
"A cat is an animal. A rat is an animal. A bat is an animal."
The pattern should match "rat" in the available string. The alert statement in the following code displays a one-element array, with one value, "rat."
<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 = /cat/;
myArray = availableString.match(re);
alert(myArray);
</script>
</body>
</html>
We have used the string match method in the statement:
myArray = availableString.match(re);
Only one match could occur in the available string; only one element was matched, therefore the returned array has only one element, "rat" as expected. If no matching occurs, null is returned; an array is not returned; the same is true with the exec() method.
Next: Extracting Continued >>
More JavaScript Articles
More By Chrysanthus Forcha