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.
1 2 3 4 5 6 |
var countryList = [ 'India', 'China', 'Bhutan']; var commaCountryList = countryList.split(','); console.log(commaCountryList); |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 |
var commaCountryList = countryList.split(','); ^ TypeError: countryList.split is not a function at Object.<anonymous> (HelloWorld.js:4:36) at Module._compile (internal/modules/cjs/loader.js:959:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10) at Module.load (internal/modules/cjs/loader.js:815:32) at Function.Module._load (internal/modules/cjs/loader.js:727:14) at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10) at internal/main/run_main_module.js:17:11 |
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.
1 2 3 4 5 6 |
var countryList = [ 'India', 'China', 'Bhutan']; var commaCountryList = countryList.toString().split(','); console.log(commaCountryList); |
Output:
1 2 3 |
[ 'India', 'China', 'Bhutan' ] |
toString()
method converted array to string and we were able to callsplit()
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.
1 2 3 4 5 6 |
var countryList = [ 'India', 'China', 'Bhutan']; var commaCountryList = typeof countryList === 'string' ? countryList.split(','):''; console.log(commaCountryList); |
Output:
1 2 3 |
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.
1 2 3 4 |
var str = document.location; var splitArr = str.split('/'); |
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
.
1 2 3 4 |
// you'll see that it will print Object console.log(typeof document.location); |
To solve the issue, convert document.location
to string first.
Here is one of the solution:
1 2 3 4 |
var str = document.location + ''; var splitArr = str.split('/'); |
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
.