Borislav Hadzhiev
Last updated: Oct 20, 2021
Check out my new book
The "match is not a function" error occurs when the match
method is called
on a value that is not of type string. To solve the error, make sure to only
call the match
method on strings, e.g. 'ABC'.match(/[A-Z]/g)
.
Here is an example of how the error occurs.
const str = {}; // ⛔️ TypeError: match is not a function const result = str.match(/[A-Z]/g);
We called the String.match method on an object and got the error back.
To solve the error, console.log
the value you're calling the match
method on
and make sure to only call the method on strings.
const str = 'Hello World'; const result = str.match(/[A-Z]/g); console.log(result); // 👉️ ['H', 'W']
If the value is not already a string, you can convert it using the toString()
method.
const num = 1234; // 👇️ use toString to convert to string first const result = num.toString().match(/[0-2]/g); console.log(result); // 👉️ ['1', '2']
Alternatively, you can check if the value is a string before calling the
match()
method.
const str = null; const result = typeof str === 'string' ? str.match(/[0-2]/g) : null; console.log(result); // 👉️ null
We used a ternary operator to check if the str
variable stores a string.
If it does, the value to the left of the comma is returned, otherwise the value to the right is returned.
match
method on it, otherwise we return a null
value.If the error persists, console.log
the value you're calling the match
method
on and check it's type using the typeof
operator.
If the value is an object, there's a very good chance that you are forgetting to
access a specific property on which you need to call the match()
method.