Tue Oct 19 2021·2 min read
Photo by Aliunix
The "split is not a function" error occurs when we call the
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.
Here is an example of how the error occurs.
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
const str = new Date(); console.log(typeof str); // 👉️ object const result = str.toString().split(' '); console.log(result); // 👉️ ['Fri', 'Dec', ...]
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
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.
splitmethod on it, otherwise we return an empty string to be consistent.
If the error persists,
console.log the value you're calling the
on and check it's type using the
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