RegExp.prototype.test()

regexp.test(string)

Returns true when the string contains a match with the pattern. The fastest way to test a string when you do not need the matched part.

Parameters

  • string – the tested string.

Return value

true or false.

Examples

const phone = /^(\+1 ?)?\d{3}[ -]?\d{3}[ -]?\d{4}$/;
console.log(['555 123 4567', '+15551234567', '555123456'].map((p) => phone.test(p)));
console.log(/coffee/i.test('COFFEE'), /^coffee$/.test('coffeehouse'));

Output:

[ true, true, false ]
true false

With the g flag the expression continues from the last match – repeated tests of the same string alternate the result:

const digit = /\d/g;
console.log(digit.test('a1'), digit.test('a1'), digit.test('a1'));
console.log(digit.lastIndex);

Output:

true false true
2

Things to watch out for

  • Do not use an expression with the g (or y) flag for tests, especially when you test it repeatedly – it causes random-looking errors (see the example).
  • Without ^ and $ a match anywhere in the string is enough – write them to check the whole input.

Browser support

Baseline – widely available: works in all major browsers and has for a long time (since 2015 at the latest). Since version: Chrome 1, Firefox 1, Safari 1; Node.js 0.10.0. As of October 2026 (MDN browser-compat-data).

Related:
RegExp
RegExp.prototype.exec()
String.prototype.search()