Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

RegExp.prototype.test

Checks whether a string matches a pattern.

Available since: ES3

Syntax

regex.test(str)

Parameters

ParameterTypeDescription
strstringThe string to search in.

Return value

booleantrue if a match is found.

Examples

Does the string contain a digit:

console.log(/\d/.test('abc1'));
console.log(/\d/.test('abc'));

Output:

true
false

A simple postal code format check:

const zip = /^\d{5}$/;
 
console.log(zip.test('10115'));
console.log(zip.test('1011'));
console.log(zip.test('10115a'));

Output:

true
false
false

Notes

Without ^ and $ the pattern matches anywhere in the string. To validate the whole string always add them.

Be careful with the g flag: such a regex remembers its position in lastIndex, and calling test() again on the same string may return false.

See also

Related recipes

In the tutorial

  • Regular expressions — Regular expressions in JavaScript for beginners: patterns, flags, character classes, testing, finding and replacing text.

Thanks for reading!

Donate to the site — we work hard for you.