Regular Expressions and RegExp
Regular expressions are arrangements of characters that form a pattern that can then be used against strings to find matches, make replacements, or locate specific substrings. Most programming languages support some form of regular expressions, and JavaScript is no exception.
Regular expressions can be created explicitly using the RegExp object, although you can also create one using a literal,
as was demonstrated with the string literal in the last section. The
following using the explicit option:
var searchPattern = new RegExp('+s');While the next line of code demonstrates the literal RegExp option:
var searchPattern = /+s/;
In both cases, the plus sign(+) in the search pattern matches
anything with one or more consecutive s’s in a
string. The forward slashes with the literal, (/+s/), mark that the object being created is a
regular expression and not some other type of object.
The RegExp Methods: test and exec
The RegExp object has only
two unique methods of interest: test and exec. The test method determines whether a string
passed in as a parameter matches with the regular expression. In the
following example, the pattern /JavaScript rules/ is tested against the string to see
whether a match is found:
var re = /JavaScript rules/;
var str = "JavaScript rules";
if (re.test(str)) document.writeln("I guess it does rule") ;Matches are case-sensitive: if the pattern is instead /Javascript rules/,
the result is false. To instruct the pattern-matching functions ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access