• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

1. Strings > 1.6. Testing String Containment with Regular Expressions

Testing String Containment with Regular Expressions

NN 4, IE 4

Problem

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

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.

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:


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint