Entry
How do I match a regexp pattern with a string?
How do I test if a certain pattern is contained in a given string?
Oct 6th, 2006 12:51
Daniel LaLiberte, Rey Nuņez,
JavaScript 1.2 includes two methods for these:
- the regexp.test() method, which returns a Boolean value that
indicates whether or not a pattern exists in a searched string, and;
- the string.match() method, which returns, as an array, the results
of
a search on a string using a supplied regular expression object.
Typical syntax is:
pattern.test(string)
string.match (/pattern/modifiers)
Typically, the test method, which returns true if the regular
expression exists within the string, is used to direct program flow.
var found = pattern.test(str)
if (found)
// a match occurred
else
// no match occurred
The sample below shows a simple use of the match method. The function
returns an array of the match(es) found, if successful, and null
otherwise.
<script language="JavaScript1.2">
<!--
function matchMe(re, str) {
var pattern = new RegExp (re,'ig');
alert (str.match(pattern))
}
//-->
</script>
To test, type different patterns to match in the first text box, and
the test string in the second.
<div align="center">
<form onsubmit="matchMe(re.value, test.value); return false">
<table cellpadding=10 cellspacing=0 border=0 bgcolor="khaki">
<tr>
<td>Match pattern:<br><input name="re"></td>
<td>Test string:<br><input name="test"></td></tr>
<tr>
<td colspan=2 align="center"><input type="submit"
value="Match"></td></tr>
</table></form></div>
If you use a regular expression stored in a variable more than once,
be sure to reset the lastIndex property to 0 after each match (or
before the next match). Otherwise the next match will start at the
character position of the end of the previous match.
var pattern = /java/i;
pattern.test("JavaScript"); // Returns true
pattern.lastIndex = 0;
pattern.test("ECMAScript"); // Returns false