SyntaxStudy
Sign Up
JavaScript Searching Strings with Regex
JavaScript Intermediate 8 min read

Searching Strings with Regex

Searching Strings with Regular Expressions

Regular expressions give you expressive pattern-matching power far beyond simple substring searches. JavaScript integrates regex tightly into its string API, so you can search, test, and extract matches with a handful of methods.

String.search()

search(regex) returns the index of the first match, or -1. It is like indexOf but accepts a regex pattern instead of a plain string.

String.match()

match(regex) returns an array of matched results. Without the global flag it returns the first match plus capture groups. With the g flag it returns an array of all matches but no capture groups. Returns null when nothing matches.

String.matchAll()

matchAll(regex) requires a global regex and returns an iterator of all matches, each including capture groups. This is the most powerful extraction method available.

RegExp.test()

/pattern/.test(str) returns a boolean and is the fastest way to validate that a string matches a pattern.

Example
const str = 'Call 123-456-7890 or 987-654-3210';
const phoneRegex = /\d{3}-\d{3}-\d{4}/g;
console.log(str.search(/\d/));    // 5
console.log(str.match(phoneRegex)); // ['123-456-7890', '987-654-3210']
const emailTest = /^[\w.-]+@[\w.-]+\.\w+$/;
console.log(emailTest.test('user@example.com')); // true
console.log(emailTest.test('bad-email'));         // false
const dated = '2024-01-15 and 2024-03-22';
const dateRx = /(\d{4})-(\d{2})-(\d{2})/g;
for (const m of dated.matchAll(dateRx)) {
  console.log(m[1], m[2], m[3]); // year month day
}
Pro Tip

Use matchAll() instead of looping with exec() — it is cleaner, avoids stateful lastIndex bugs, and works naturally with for...of.