test and match
Learn to check a match with test and extract matches with match.
The .test() method
The .test() method of a RegExp returns true when the pattern matches the string and false otherwise. The result is always a boolean.
const re = /\d/;
re.test("abc5"); // true
re.test("abc"); // falseWhen you only need to ask "does this text match this pattern?", test is the fastest way. Use it when you do not need to extract the matched part.
The .match() method
The .match() method of a string extracts the matched part. It returns null when there is no match, and an array when there is. The first item of the array is the full match.
"date 2024".match(/\d+/);
// ["2024", ...]Add the g flag and you get an array of all matches. This lets you pull every number, code or tag out of a text in one call.
Exercise Extract the first word
Assign the first matching word to firstWord using sentence.match(). Use \w+ for the word pattern. Then log firstWord[0] with console.log.
Show example solution
The match method takes a regex and returns the match as an array. Use \w+ for a word.
Example solution:
let firstWord = sentence.match(/\w+/);
console.log(firstWord[0]);
Test yourself
-
What does the .test() method of a RegExp return?
- a string
- a boolean (true/false)
- a number
- an array
Show answer
a boolean (true/false) — Correct! .test() always returns true or false.
-
Call the test method
const re = /\d/; const found = re.____("abc5"); console.log(found);Show answer
const re = /\d/; const found = re.test(("abc5"); console.log(found); -
Match methods with their result
- .test()
- true/false
- .match()
- first match
- .exec()
- next match
- /g flag
- finds all