Solve - regex test is not a function Error in JavaScript


Borislav Hadzhiev

Wed Oct 20 20211 min read

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.

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.

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.

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 expose a test() method.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee