JavaScript RegExp Methods

JavaScript provides several methods for working with regular expressions. Some are methods on the RegExp object itself, while others are String methods that accept a regex as an argument.

test() and exec()

These are methods on the RegExp object. test() returns a boolean, while exec() returns detailed match information or null.

test() and exec()
const regex = /\d+/g;
const str = 'Order 42 has 3 items';

// test() returns true/false
console.log(/\d+/.test(str)); // true
console.log(/\d+/.test('no numbers')); // false

// exec() returns match details
const regex2 = /\d+/g;
let match;
while ((match = regex2.exec(str)) !== null) {
  console.log(`Found '${match[0]}' at index ${match.index}`);
}
// Found '42' at index 6
// Found '3' at index 13
📝 Note: When using exec() with the global (g) flag, it updates the regex's lastIndex property. Call it repeatedly in a loop to find all matches.

match() and matchAll()

These are String methods. match() returns an array of matches, while matchAll() returns an iterator with detailed match objects including capturing groups.

match() and matchAll()
const str = 'Call 555-1234 or 555-5678';

// match() without global flag — returns first match with details
const single = str.match(/(\d{3})-(\d{4})/);
console.log(single[0]); // '555-1234'
console.log(single[1]); // '555'
console.log(single[2]); // '1234'

// match() with global flag — returns all matches (no groups)
const all = str.match(/(\d{3})-(\d{4})/g);
console.log(all); // ['555-1234', '555-5678']

// matchAll() — returns iterator with group details
const matches = [...str.matchAll(/(\d{3})-(\d{4})/g)];
matches.forEach(m => {
  console.log(`Full: ${m[0]}, Area: ${m[1]}, Number: ${m[2]}`);
});
// Full: 555-1234, Area: 555, Number: 1234
// Full: 555-5678, Area: 555, Number: 5678

replace() and replaceAll()

The replace() method returns a new string with the first match (or all matches with /g flag) replaced. replaceAll() replaces every occurrence without needing the global flag.

replace() and replaceAll()
const str = 'Hello World, Hello JavaScript';

// replace() — first occurrence only
console.log(str.replace(/Hello/, 'Hi'));
// 'Hi World, Hello JavaScript'

// replace() with global flag
console.log(str.replace(/Hello/g, 'Hi'));
// 'Hi World, Hi JavaScript'

// replaceAll() with regex (must have g flag)
console.log(str.replaceAll(/Hello/g, 'Hi'));
// 'Hi World, Hi JavaScript'

// Using capture groups in replacement
const date = '2024-01-15';
const reformatted = date.replace(/(\d{4})-(\d{2})-(\d{2})/, '$2/$3/$1');
console.log(reformatted); // '01/15/2024'

// Using a function for replacement
const result = 'hello world'.replace(/\b\w/g, char => char.toUpperCase());
console.log(result); // 'Hello World'

search() and split()

search() returns the index of the first match (or -1 if not found). split() divides a string into an array using a regex as the delimiter.

search() and split()
// search() returns index of first match
const str = 'The price is $42.99';
console.log(str.search(/\d/));    // 14
console.log(str.search(/xyz/));   // -1

// split() with regex
const data = 'one, two;  three   four';
const words = data.split(/[,;\s]+/);
console.log(words); // ['one', 'two', 'three', 'four']

// split() with capturing group keeps delimiters
const parts = 'Hello---World===JavaScript'.split(/(---)/);
console.log(parts);
// ['Hello', '---', 'World===JavaScript']

// split() with limit
const limited = 'a-b-c-d-e'.split(/-/, 3);
console.log(limited); // ['a', 'b', 'c']

Capturing Groups and Named Groups

Capturing groups (...) save matched text for later use. Named groups (?...) give groups meaningful names, making regex results easier to work with.

Capturing Groups and Named Groups
// Numbered capturing groups
const dateRegex = /(\d{4})-(\d{2})-(\d{2})/;
const match = '2024-03-15'.match(dateRegex);
console.log(match[1]); // '2024' (group 1)
console.log(match[2]); // '03'   (group 2)
console.log(match[3]); // '15'   (group 3)

// Named capturing groups
const namedRegex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const named = '2024-03-15'.match(namedRegex);
console.log(named.groups.year);  // '2024'
console.log(named.groups.month); // '03'
console.log(named.groups.day);   // '15'

// Named groups in replace()
const result = '2024-03-15'.replace(
  /(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})/,
  '$<m>/$<d>/$<y>'
);
console.log(result); // '03/15/2024'

// Destructuring named groups
const { groups: { year, month, day } } = namedRegex.exec('2024-03-15');
console.log(`${year}, ${month}, ${day}`); // '2024, 03, 15'
MethodCalled OnReturnsNotes
test()RegExpBooleanSimple match check
exec()RegExpArray or nullDetailed match with groups
match()StringArray or nullWithout /g: details. With /g: all matches
matchAll()StringIteratorAll matches with full details (requires /g)
replace()StringNew stringFirst match or all with /g
replaceAll()StringNew stringAll matches (requires /g with regex)
search()StringNumberIndex of first match or -1
split()StringArraySplit string by regex pattern
Exercise:
What does matchAll() require in the regex?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.