[Solved] TypeError: substring is not a function in JavaScript

The TypeError: substring is not a function is one of the most common errors in JavaScript. This error occurs when the substring() method is called on a value that is not a string. To solve the error, convert the value to a string before calling the substring method otherwise only call the method on strings.

In this article, you’ll learn everything about this TypeError: substring is not a function in JavaScript. And how to resolve the error all the possible solutions with examples.

What is TypeError: substring is not a function error?

Let’s look at a simple example to illustrate this problem

const str = 1234567890
const output = str.substring(1, 4)
console.log(output)

Output

TypeError: str.substring is not a function

How To Fix TypeError: substring is not a function Error?

# Convert the value to a string before calling substring()

We can easily resolve this error by converting the value to a string before calling the substring() method.

const value = 123456;


const result = String(value).substring(0, 3);

console.log(result); 

Output

123

If you know that the value can be converted to a valid string, use the String() constructor before calling the String.substring() method.

# Check if the value is of type string before calling substring()

You can check if the value has a type of string before calling the substring method.

const str = "Hello Cary"

// Convert to string and then call substring
const result = typeof str === 'string' ? str.substring(5, str.length) : "";
console.log(result)

Output

Cary

We have used the ternary operator, which is very similar to an if/else statement.

You can also use the if statement.

const str = "Hello Cary"

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

Cary

Conclusion

The “TypeError: substring is not a function” occurs when Called the substring() method on a value is not a string.

To solve this error, convert the value into string before calling the substring() method or only call the method on strings.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Categories