Searching for Substrings
Problem
You need to search for a substring, and return either the starting position of the match or the matching value itself.
Solution
There are several ways to accomplish this using regular expressions. Some methods are called on a RegExp
pattern or object and some are called on String
objects.
RegExp
objects
The first way is to call the test
method on a RegExp
pattern or object. The test
method returns a boolean value:
The next way to is to call the exec
method on a RegExp
pattern or object. The exec
method returns an array with the match information or null
:
String
objects
The match
method matches a given string with the RegExp
. With āgā flag returns an array containing the matches, without āgā flag returns just the first match or if no match is found returns null
.
The search
method matches RegExp
with string and returns the index of the beginning of the match if found, -1 if not.
Discussion
Regular Expressions are a powerful way to test and match substrings.