Regular expressions are used to find patterns in strings.
Tests
Like almost everything else in JavaScript, a regular expression is an object. You can create one using the RegExp constructor or by enclosing a pattern in forward sloshes.
new RegExp("hello");
/hello/;
The simple regular expression above just looks for an “h” followed by an “e” and so on.
/hello/.test("hello, world");
/hello/.test("regular");
The test method checks the string for the pattern, regardless of the position of the string.
/[1234]/.test("5552277")
/[1-4]/.test("5552277")
Any character in brackets is tested. If any of the characters appear in the string, the test is true.
The dash represents a range when it appears in square brackets.
/\d/.test("1st place")
The backslash and lower case d is shorthand for [0123456789].
/\d/.test("h")
You can also use the shortcut groups in brackets.
/[^\dh]/.test("Twenty 1") // true
In brackets, the caret tells the test to fail if only the test characters are present and succeed if there are any other characters besides the test characters.
\d matches any digit once.
/'\d+'/.test("1225")
The plus sign, in this case, matches any digit multiple times. This will reveal its usefulness later on.
/hel?lo/.test('hello');
A question mark makes a character optional.
/hel{2}o/.test("hello")
Indicate how many times an element (character/sign) should match.
/hel{1,}o/.test('helllllo')
/one+(two+)/i.test('oneeeetwotwotwo')
To apply + or * to a group of elements, wrap the elements in parenthesis and place the sign after the last element (and before the closing parenthesis).
The i makes the test case insensitive.
Matches and Groups
The test method tells us if the pattern was found.
The exec method gives us an object with more information.
/one+(two+)/i.exec('oneeeetwotwotwo')
Find the characters o and n, plus any number of e’s that follow o and n, plus any number of “two” that follow any number of e’s.
^
When the caret is used with brackets, it means match any characters except for the characters that come after the caret.
/[^a]/.test('b') // true
The search succeeds if there is a character that is not a.
/[^a]/.exec('b') // ['b']
/[^a]/.test('a') // false
When the caret is not used inside of brackets, it means that the search starts at the beginning of the string.
/^a/.test('animal') // true
The search succeeds because the a is at the beginning of the string.
/^a/.exec('animal') // ['a']
/^a/.test('bat') // false
The search fails because the a in bat is not at the beginning.
The caret means two completely different things in and outside of brackets.
/'([^']*)'/.test("'hello'");
[^’]
Succeed if any other character besides a quote appears at least once.
/[^']/.test("b");
This passes because a character besides a quote appears in the string.
/[^']/.test("'");
This fails because only a single quote appears in the string.
/[^']*/.test("'");
This does not fail because the star means that the search can appear 0, 1, or more than 1 times.
With exec, the whole match is always the first element. The second element is the first group, and so on.
If the group is found multiple times, the element in the array is just the last match.
/one+(two+)/i.exec('oneeeetwotwotwo') // Array [ "oneeeetwo", "two" ]
The first element is the whole match.
The Date Class
new Date (); // The current date/time
Get the current date. The Date class has many methods to help with time and dates.
new Date (2010, 11, 10);
Get a specific date. Month numbers start at 0, but days start at 1.
new Date (2005, 05, 20).getTime();
The set time method returns the date in milliseconds. This is known as a timestamp.
let [_, month, day, year] = /(\d{1,2})-(\d{1,2})-(\d{4})/.exec(string);
new Date(year, month - 1, day);
We can use regex to extract date numbers from a string. The underscore can be used if we don’t care about a value at a certain position in the array.
/^\d+$/
Match a string composed entirely of digits. Use a caret and a dollar sign to signify you want the match to span the entire string from beginning (^) to end ($).
/\belect\b/.test("electric"); // false
Verify the match starts at a ward boundry.
Choice Patterns
let animalCount = /\b\d+(pig|cow|chicken)s?\b/;
Look for a number followed by the word pig, cow, or chicken, and an optional s.
animalCount.test("15 pigs");
animalCount.test("10 pigcows");
Backtracking
The RegEx engine is like a recursive loop that moves forward one character at a time for each test. It’s possible to write tests that require a lot of memory.
The Replace Method
"ringer".replace("r", "d");
The first argument can be a regular expression.
“ringer”.replace(/r/g, “d”);
The g option means replace all occurrences.
“Smith, John\nSmith, Jane”.replace(/(\w+), (\w+)/g, “$2 $1”) // John Smith\nJane Smith
The dollar and number refer to the groups.
Greed
Add a question mark after repetition operators to stop them from being greedy.
(+?, *?, ??, {}?)
The Search Method
console.log(" word".search(/\S/));
The last Index property
Set the lastIndex property to control where to start searching with exec. The global or sticky option needs to be set.
Only use global option with replace and lastIndex.