If we call the substring()
method on the value that is not of a string type, JavaScript will throw a TypeError: substring is not a function.
In this tutorial, we will look at what is TypeErrror: substring is not a function error and how to resolve them with examples.
What is TypeError: substring is not a function error?
Let us take a simple example to demonstrate this issue
const str = 1234567890
const output = str.substring(2, 3)
console.log(output)
Output
TypeError: str.substring is not a function
In the above example, we have declared a variable and assigned the integer value into it.
In the next statement, we call the String.substring()
method on the value of the type number, and hence we get a TypeError: substring is not a function.
We can also check the variable type using typeof()
to confirm the datatype.
const str = 1234567890
console.log("The type of variable is",typeof str)
Output
The type of variable is number
How to fix TypeError: substring is not a function error?
The substring()
method returns the part of the string
between the start and end indexes, or to the end of the string. The String.prototype.substring()
method can only be used on the string values and not on any other types.
There are two ways to fix this issue in JavaScript.
Solution 1: Convert the value into a string
We can easily resolve the issue by converting the value into a string before calling the substring()
method.
If we know the value can be converted to a valid string, then we can use the toString()
method in JavaScript that returns the string representing the object.
Let us take an example to resolve the issue using the toString()
method.
const str = 1234567890
// Convert to string and then call substring()
const output = str.toString().substring(2, 7)
console.log(output)
Output
34567
Solution 2 – Performing the type check
We can also perform a type check on the variable to check if it’s a string before calling the substring()
method.
Example – Type check using if/else
const str = "Hello World"
if (typeof str === 'string') {
// Convert to string and then call substring
const output = str.substring(6, str.length)
console.log(output)
}
else {
console.log("The object is not a valid string")
}
Output
World
Example – Type check using ternary operator
const str = "Hello World"
// Convert to string and then call substring
const result = typeof str === 'string' ? str.substring(5, str.length) : "";
console.log(result)
Output
World
Conclusion
The TypeError: substring is not a function occurs if we call a substring()
method on the value that is not of a type string. We can resolve the issue by converting the value into string before calling the substring()
method or by performing a type check; we can mitigate this error.