Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Aliunix
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.
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 toString()
method.
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
split()
method.
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.
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.