Borislav Hadzhiev
Reading time·2 min
Photo from Unsplash
The "TypeError: substring is not a function" occurs when the substring()
method is called on a value that is not a string.
To solve the error, either convert the value to a string before calling the
substring
method or only call the method on strings.
Here is an example of how the error occurs.
const str = 123456; // ⛔️ Uncaught TypeError: str.substring is not a function const result = str.substring(0, 3);
We called the
String.substring()
method on a value of type number
which caused the error.
substring()
We can convert the value to a string before calling the substring()
method to
solve the error.
const value = 123456; // ✅ Works const result = String(value).substring(0, 3); console.log(result); // 👉️ "123"
If you know that the value can be converted to a valid string, use the
String()
constructor before calling the String.substring()
method.
substring()
Alternatively, you can check if the value has a type of string before calling
the substring
method.
const str = null; const result = typeof str === 'string' ? str.substring(0, 3) : ''; console.log(result); // 👉️ ""
We used the ternary operator, which is very similar to an if/else
statement.
You can also use a simple if
statement to achieve the same result.
const str = null; let result = ''; if (typeof str === 'string') { result = str.substring(0, 3); } console.log(result); // 👉️ ""
We check if the str
variable stores a string. If it does, we return the result
of calling the substring
method, otherwise, we return an empty string.
console.log
the value you're calling the substring()
method on and make sure it's a valid string.If the value is an object or an array, you should probably be accessing a
specific object property or a specific array index before calling the
substring()
method.
// ✅ with objects const obj = { name: 'bobbyhadz.com', }; const str1 = obj.name.substring(0, 3); console.log(str1); // 👉️ bob // -------------------------------------- // ✅ with arrays const arr = ['bobby', 'hadz', 'com']; const str2 = arr[0].substring(0, 3); console.log(str2); // 👉️ bob
We accessed the name
property on the object and the first array element before
calling the String.substring()
method.
The String.substring() method returns a slice of the string from the start index to the excluding end index.
The method takes the following parameters:
Name | Description |
---|---|
start index | The index of the first character to include in the returned substring |
end index | The index of the first character to exclude from the returned substring |
If no end
index is specified the slice goes to the end of the string.