Solve - substring is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Jacek Dylag

Solve - substring is not a function Error #

The "substring is not a function" error 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.

typeerror substring is not a function

Here is an example of how the error occurs.

index.js
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, so we got the error back.

To solve this, we can convert the value to a string before calling the substring() method.

index.js
const str = 123456; // โœ… Works const result = str.toString().substring(0, 3); console.log(result); // ๐Ÿ‘‰๏ธ "123"

If you know that the value can be converted to a valid string, you can safely call the toString() method on it before calling substring.

Alternatively, you can check if the value has a type of string before calling the substring method.
index.js
const str = null; const result = typeof str === 'string' ? str.substring(0, 3) : ''; console.log(result); // ๐Ÿ‘‰๏ธ ""

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

If the expression to the left of the question mark evaluates to a truthy value, we return the value to the left of the colon, otherwise the value to the right is returned.

We check if the str variable stores a string. If it does, we return the result from calling the substring method on it, otherwise we return an empty string to be consistent.

If the error still persists, console.log the value you're calling thesubstring method on and also log its type using the typeof operator.

If the value is an object or array, you should probably be accessing a specific property on the object or a specific index in the array, which stores a string, before calling the substring() method.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee