DekGenius.com
[ Team LiB ] Previous Section Next Section

1.6 Testing String Containment with Regular Expressions

NN 4, IE 4

1.6.1 Problem

You want to use regular expressions to know whether one string contains another.

1.6.2 Solution

Create a regular expression with the short string (or pattern) and the global (g) modifier. Then pass that regular expression as a parameter to the match( ) method of a string value or object:

var re = /a string literal/g;
var result = longString.match(re);

When a global modifier is attached to the regular expression pattern, the match( ) method returns an array if one or more matches are found in the longer string. If there are no matches, the method returns null.

1.6.3 Discussion

To work this regular expression mechanism into a practical function, you need some helpful surrounding code. If the string you are looking for is in the form of a string variable, you can't use the literal syntax for creating a regular expression as just shown. Instead, use the constructor function:

var shortStr = "Framistan 2000";
var re = new RegExp(shortStr, "g");
var result = longString.match(re);

After you have called the match( ) method, you can inspect the contents of the array value returned by the method:

if (result) {
    alert("Found " + result.length + " instances of the text: " + result[0]);
} else {
    alert("Sorry, no matches.");
}

When matches exist, the array returned by match( ) contains the found strings. When you use a fixed string as the regular expression pattern, these returned values are redundant. That's why it's safe in the previous example to pull the first returned value from the array for display in the alert dialog box. But if you use a regular expression pattern involving the symbols of the regular expression language, each of the returned strings could be quite different, but equally valid because they adhere to the pattern.

As long as you specify the g modifier for the regular expression, you may get multiple matches (instead of just the first). The length of the array indicates the number of matches found in the longer string. For a simple containment test, you can omit the g modifier; as long as there is a match, the returned value will be an array of length 1.

1.6.4 See Also

Section 1.0.2 in the introduction to this chapter; Recipe 8.2 for using regular expressions in form field validations.

    [ Team LiB ] Previous Section Next Section