TypeError: split is not a function in JavaScript

TypeError: .split is not a function occurs when we call split() function on object which is not an string. split() function can be only called on string. To resolve this issue, convert value to string using toString() ,method before calling split().

Let’s see with help of simple example.

Output

We got this error because countryList is not an string, it is an array.

Convert countryList to string using toString() method and it should work as expected.

Output:

toString() method converted array to string and we were able to call split() method on it.

You can also check if it is type of string before calling split() to make sure that split() is being called on string only.

Output:

As you can see countryList is not a string, so result is empty string.

We used ternary operator to check if countryList is string or not. If it is a string, call the split() method, otherwise return empty string.

If you are getting this issue, while working on document.location object then you need to first convert document.location to string using toString() method before calling split() method.

When you execute the code, you will get TypeError: .split is not a function as we are calling split() on document.location rather than string object.

If you print typeof for document.location, it will print object.

To solve the issue, convert document.location to string first.

Here is one of the solution:

Notice + '' at the end, it will convert document.location to string and we can call split() method on it.

Read also: map is not a function in JavaScript.

That’s all about how to resolve TypeError: split is not a function in JavaScript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *