Solve - regex match is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 20, 2021

banner

Check out my new book

Solve - regex match is not a function Error #

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).

typeerror regex match is not a function

Here is an example of how the error occurs.

index.js
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.

index.js
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.

index.js
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.

index.js
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.

If the value is a string, we return the result from calling the 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.

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