Advertisement
Advertisement


What is causing the error `string.split is not a function`?


Question

Why am I getting...

Uncaught TypeError: string.split is not a function

...when I run...

var string = document.location;
var split = string.split('/');

2018/10/23
1
110
10/23/2018 1:54:18 PM

Accepted Answer

Change this...

var string = document.location;

to this...

var string = document.location + '';

This is because document.location is a Location object. The default .toString() returns the location in string form, so the concatenation will trigger that.


You could also use document.URL to get a string.

2012/04/13
217
4/13/2012 6:10:59 PM


run this

// you'll see that it prints Object
console.log(typeof document.location);

you want document.location.toString() or document.location.href

2012/11/16

document.location isn't a string.

You're probably wanting to use document.location.href or document.location.pathname instead.

2012/04/14

In clausule if, use (). For example:

stringtorray = "xxxx,yyyyy,zzzzz";
if (xxx && (stringtoarray.split(',') + "")) { ...
2020/07/26