Solve - split is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Aliunix

Solve - split is not a function Error #

The "split is not a function" error occurs when we call the split() method on a value that is not of type string. To solve the error, convert the value to a string using the toString() method before calling the split method or make sure to only call the split method on strings.

typeerror split is not a function

Here is an example of how the error occurs.

index.js
const str = new Date(); // ⛔️ Uncaught TypeError: str.split is not a function const result = str.split(' ');

We called the String.split method on an object and got the error back.

To solve the error, make sure to only call the split() method on strings. You can convert most values to a string by using the toString() method.

index.js
const str = new Date(); console.log(typeof str); // 👉️ object const result = str.toString().split(' '); console.log(result); // 👉️ ['Fri', 'Dec', ...]
The toString() method converted the date object to a string, so we were able to call the split() method on it.

Alternatively, you can check if the value is a string before calling the split() method.

index.js
const str = 100; const result = typeof str === 'string' ? str.split(' ') : ''; console.log(result); // 👉️ ""

We used a ternary operator to check if the str variable stores a string.

If it does, the value to the left of the comma is returned, otherwise the value to the right is returned.

If the value is a string, we return the result from calling the split method on it, otherwise we return an empty string to be consistent.

If the error persists, console.log the value you're calling the split method on and check it's type using the typeof operator.

If the value is an object, there's a very good chance that you are forgetting to access a specific property on which you need to call the split() method.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.