Testing & Matching in JavaScript
From the JavaScript Regular Expressions cheat sheet · String Methods · verified Jul 2026
Testing & Matching
Methods for pattern matching
javascript
// test() - Returns boolean
/\d+/.test("123") // true
/[a-z]+/.test("ABC") // false
// match() - Returns array or null
"hello".match(/[aeiou]/g) // ['e', 'o']
"hello".match(/(\w)(\w+)/) // ['hello', 'h', 'ello']
// matchAll() - Returns iterator of all matches
const matches = "cat bat rat".matchAll(/(\w)at/g)
for (const match of matches) {
console.log(match[0], match[1]) // 'cat' 'c', 'bat' 'b', etc
}
// search() - Returns index or -1
"hello world".search(/world/) // 6
"hello world".search(/foo/) // -1
// exec() - Returns match with details
const regex = /(\d{4})-(\d{2})/g
let match
while (match = regex.exec("2024-03-15 2025-04-20")) {
console.log(match[0]) // "2024-03", "2025-04"
console.log(match.index) // 0, 11
}💡 Use test() when you only need true/false
⚡ matchAll() requires global flag and returns iterator
📌 exec() with g flag remembers position via lastIndex
🟢 match() without g returns groups, with g returns all matches
methodstestingmatching