How to Resolve "TypeError: .match is not a function" Error in JavaScript
The TypeError: x.match is not a function is a common error that occurs when you try to call the String.prototype.match() method on a value that is not a string. This typically happens when you mistakenly assume a variable holds a string, but it actually holds a number, an object, null, or undefined.
This guide will explain the common scenarios that cause this error and show you the correct, modern solutions for both guarding against the error and correctly performing a match on your data.
The Core Problem: .match() is a String-Only Method
The .match() method is a function that exists exclusively on the String.prototype. It is designed to retrieve the result of matching a string against a regular expression. It does not exist on any other data type. When you try to call it on a number, an array, a plain object, null, or undefined, JavaScript throws a TypeError.
Example of problem:
// Problem: `myData` is an object, not a string.
let myData = { id: 123 };
// ⛔️ TypeError: myData.match is not a function
let result = myData.match(/\d+/);
The key to solving this error is to ensure you are only calling .match() on a true string.
Cause 1 (Most Common): The Variable is a Number
This is a very frequent source of the error, especially when working with IDs, codes, or numerical data that you want to inspect with a regex.
Example of problem:
// Problem: `zipCode` is a number, not a string.
let zipCode = 90210;
// ⛔️ TypeError: zipCode.match is not a function
let result = zipCode.match(/^\d{5}$/);
Solution: you must first convert the number to a string before you can call a string method on it. The String() constructor is the simplest way to do this.
let zipCode = 90210;
// ✅ Correct: First, convert the number to a string.
let zipCodeString = String(zipCode);
let result = zipCodeString.match(/^\d{5}$/);
console.log(result); // Output: ['90210', index: 0, ...]
Cause 2: The Variable is an Object or another Non-String Type
You might have an object and try to call .match() on it directly, when your intent was to match against one of its properties.
Example of problem:
// Problem: `user` is an object.
let user = { name: 'Alice', email: 'alice@example.com' };
// ⛔️ TypeError: user.match is not a function
user.match(/@/);
Solution: you must access the specific string property on the object that you intend to test.
// ✅ Correct: Call `match` on the string property.
let user = { name: 'Alice', email: 'alice@example.com' };
let hasAtSymbol = user.email.match(/@/);
if (hasAtSymbol) {
console.log('Email appears to be valid.');
}
Output:
Email appears to be valid.
Cause 3: The Variable is undefined or null
If a variable has not been initialized or a function did not return a value, it may be undefined.
Example of problem:
let myData; // `myData` is `undefined`
// ⛔️ TypeError: Cannot read properties of undefined (reading 'match')
myData.match(/a/);
Solution: guard your code to ensure you only call match on a valid string. Optional chaining (?.) is a modern and concise way to do this.
let myData; // `myData` is `undefined`
// ✅ Safe: If `myData` is null or undefined, the expression returns `undefined`.
let result = myData?.match(/a/);
console.log(result); // Output: undefined (no error thrown)
You can combine this with the nullish coalescing operator (??) to provide a default value.
// If the match is not found or the variable is nullish, default to an empty array.
let safeResult = myData?.match(/a/g) ?? [];
console.log(safeResult); // Output: []
Practical Example: A Robust Search Function
This function demonstrates how to safely perform a match, handling different data types gracefully.
function safeMatch(data, regex) {
// Guard against null and undefined
if (data == null) {
return null;
}
// Convert numbers to strings before matching
let stringToTest = String(data);
return stringToTest.match(regex);
}
// Example Usage:
console.log(safeMatch('hello', /e/)); // Output: ['e', ...]
console.log(safeMatch(12345, /\d/g)); // Output: ['1', '2', '3', '4', '5']
console.log(safeMatch(null, /a/)); // Output: null
console.log(safeMatch({}, /a/)); // Output: null
Conclusion
The TypeError: .match is not a function is a clear signal that you are trying to use a string method on the wrong data type.
- Remember that
.match()is only available for strings. - If you have a number, you must convert it to a string first:
String(myNum).match(...). - If you have an object, you must access one of its properties that is a string:
myObj.myProp.match(...). - Use optional chaining (
?.) to prevent errors when a variable might benullorundefined.