Borislav Hadzhiev
Last updated: Jul 23, 2022
Check out my new book
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')
.
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
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
implement a test()
method.