Wed Oct 20 2021·1 min read
Photo by Darren Lawrence
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.
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
const result = /[a-z]/.test('example'); console.log(result); // 👉️ true
testmethod 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
I'll send you 1 email a week with links to all of the articles I've written that week