Online Compiler logoOnline Compiler

Regex Methods in JavaScript

Regular expressions are powerful, but you need the right methods to run them, extract matches, and transform text. This page covers the most common String and RegExp APIs for working with regex patterns in JavaScript.

String Methods that Accept Regex

Several string methods accept a regular expression as the first argument. Use them when you need to search, verify, or replace parts of a string without manually iterating over matches.

Find matches with string.match()

const msg = 'Hello 123, hello 456';
const digits = msg.match(/d+/g);
console.log(digits); // ['123', '456']

const noMatch = msg.match(/xyz/);
console.log(noMatch); // null

String.match() returns an array of matches, or null when there is no match. With the global flag (g) it returns all matches.

Split a string using a regex

const csv = 'one,two,,three';
console.log(csv.split(/,/)); // ['one', 'two', '', 'three']

// Split on one or more spaces
console.log('a  b   c'.split(/s+/)); // ['a', 'b', 'c']

split() works with regex patterns, which can be especially useful when you need to split on variable whitespace or delimiters.

RegExp Methods: test() and exec()

RegExp instances have their own methods that offer fine-grained control. test() is great for boolean checks, while exec() returns rich match information including capture groups and match indexes.

Validate input with test()

const hasUppercase = /[A-Z]/;
console.log(hasUppercase.test('hello')); // false
console.log(hasUppercase.test('Hello')); // true

test() returns true or false depending on whether the pattern matches. It’s fast and easy for simple validations.

Use exec() to inspect matches

const regex = /(w+)@(w+).(w+)/;
const match = regex.exec('test@example.com');
console.log(match[0]); // 'test@example.com'
console.log(match[1]); // 'test'
console.log(match[2]); // 'example'
console.log(match[3]); // 'com'

exec() returns an array with the full match at index 0 and captured groups in subsequent indexes. It also includes the match index and input string.

When the regex has the g flag, exec() and test() advance lastIndex on each call. That can be used to iterate matches, but it means you should reset lastIndex if you reuse the regex.

Iterate matches with exec() and lastIndex

const regex = /d+/g;
let match;
while ((match = regex.exec('1 2 3')) !== null) {
  console.log('Found', match[0], 'at', match.index);
}

// Resetting lastIndex to reuse the regex
regex.lastIndex = 0;
console.log(regex.test('4')); // true

Exec can be used in a loop to walk through all matches. Remember to reset lastIndex when you need the regex for another operation.

Replacing Matches

replace() works with both strings and regex patterns. When using regex, you can refer to capture groups in the replacement string or provide a callback for more complex transformations.

Replace using capture groups

const date = '2024-03-13';
console.log(date.replace(/(d{4})-(d{2})-(d{2})/, '$2/$3/$1')); // 03/13/2024

Use $1, $2, etc. in the replacement string to reuse capture group values from the match.

Dynamic replacements with a callback

const csv = 'apple,banana,cherry';
const titleized = csv.replace(/(w)/g, (match) => match.toUpperCase());
console.log(titleized); // Apple,Banana,Cherry

When you need custom logic per match, provide a function to replace(). It receives the match, groups, index, and original string.

Common Gotchas

  • test() and global regex: With the g flag, test() advances the regex’ lastIndex each time it runs. Reset lastIndex if you need repeatable results.
  • match() can return null: Always check for null before accessing match results.
  • replace() replacement tokens: $& is the full match, $1.. are capture groups, and $$ inserts a literal $.

Next Steps

Want to explore regex patterns more? Head to the Regex Patterns page. If you'd like to test your own expressions, try the Regex Tester.