String Methods for Pattern Matching

Until now, we’ve been discussing the grammar used to create regular expressions, but we haven’t examined how those regular expressions can actually be used in JavaScript code. In this section, we discuss methods of the String object that use regular expressions to perform pattern matching and search-and-replace operations. In the sections that follow this one, we’ll continue the discussion of pattern matching with JavaScript regular expressions by discussing the RegExp object and its methods and properties. Note that the discussion that follows is merely an overview of the various methods and properties related to regular expressions. As usual, complete details can be found in the core reference section of this book.

Strings support four methods that make use of regular expressions. The simplest is search( ) . This method takes a regular expression argument and returns either the character position of the start of the first matching substring, or -1 if there is no match. For example, the following call returns 4:

"JavaScript".search(/script/i);

If the argument to search( ) is not a regular expression, it is first converted to one by passing it to the RegExp constructor. search( ) does not support global searches -- it ignores the g flag of its regular expression argument.

The replace( ) method performs a search-and-replace operation. It takes a regular expression as its first argument and a replacement string as its second argument. It searches ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.