Here’s an example of a RegExp that’s intended to blow your mind if you’ve never seen one, if you’ve seen one, you may proceed:
This is infact a RegExp for matching the HTML5 email format (what the
.test() is probably my favourite method of testing RegExps, it’s a beautiful API, the fastest and the simplest to use. The
.test() API runs a search for a match between a RegExp and a String.
.test()API returns a boolean (true/false) - returns true if your test passes (if the pattern you’re matching is present) and false if it doesn’t
.test()returns no data, so don’t expect any
.match() is best when you require or are expecting data back in a test result,
.match() returns an array with the matches, or simply
null if there are none. The matches are retrieved from a string again. With
.match(), you won’t just be testing for the presence of data, you’ll want to see if a data pattern exists, and return that data. An example might be matching a credit card’s four-digit pattern and returning those digits.
- Returns an array of matches
- Generally doesn’t describe the actual data you want, uses capture groups
- Capture groups match your data, and return the data inside the group to you
- Think of it as a kind of validator
- Can look the same as
You can access items in the array instantly by specifying the index:
Exec is similar to
.match(), although it actually returns the part of the string you were looking to match. For instance, if I wanted to search a string for the word ‘Todd’, I could get it returned if it matches.
- Returns the matching pattern, almost ‘removing it from a string’
You’ll notice I added in the
/i at the end, this means it’s not case sensitive.
Very similar to the
.exec() method, but using
.search() will tell you the index value of where the match was found.
- Returns the matching pattern’s index value, how far into the string it occurred
Split is absolutely perfect for neat little tricks when dealing with returned data, using
.split() will cut your string into two (or more) pieces.
- Great for splitting chunks of data
- Returns a new array
Here’s an example of splitting a string by its RegExp equivalent of whitespace:
It’s also interesting to note, that doing the following still produce the same result and pass the if statement check: