Solve - regex test is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 23, 2022

banner

Check out my new book

Solve - regex test is not a function Error #

The "test is not a function" error occurs when the test() method is called on a value that is not a regular expression, e.g. a string. To solve the error, make sure to only call the test method on regular expressions, e.g. /[a-b]/.test('abc').

typeerror regex test is not a function

Here is an example of how the error occurs.

index.js
const regex = '[a-z]'; // ⛔️ TypeError test is not a function const result = regex.test('example');

We called the RegExp.test() method on a string and got the error back.

To solve this, make sure to only call the test() method on regular expressions.

index.js
const result = /[a-z]/.test('example'); console.log(result); // 👉️ true
The test method can only be called on valid regular expressions. The method checks if there is a match between the regular expression and the string and returns the result.

Notice that the regular expression is not wrapped in a string.

The forward slashes / / mark the beginning and end of the regex.

When storing the regular expression in a variable, make sure to not wrap it in quotes.

index.js
const regex = /[a-z]/; const result = regex.test('example'); console.log(result); // 👉️ true

If the regex is wrapped in quotes, it becomes a string and strings don't implement a test() method.

Use the search field on my Home Page to filter through my more than 3,000 articles.