152

Why am I getting...

Uncaught TypeError: string.split is not a function

...when I run...

var string = document.location;
var split = string.split('/');
erikvimz
  • 5,256
  • 6
  • 44
  • 60

5 Answers5

268

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.

kapa
  • 77,694
  • 21
  • 158
  • 175
  • 78
    Would not it be cleaner to call `toString()` instead of hacky concatenation? – kapa Apr 13 '12 at 18:11
  • 5
    @bažmegakapa: Yeah, that's a matter of preference. The `+ ''` is a pretty common trick for string coercion, but some people prefer the `toString()` method. I wouldn't consider it any more hacky than using the unary `+` for number conversion. –  Apr 13 '12 at 18:13
  • 4
    That is just as ugly. There is `parseInt()` and `parseFloat()`. There is also `Number()`. The `+` is shorter of course, but less readable for someone not used to hacky code or less experienced. – kapa Apr 14 '12 at 07:52
  • the `+ ''` method doesn't change anything for me in Chrome Browser but `toString()` does. – Martin Schneider Sep 23 '16 at 08:46
  • @MA-Maddin: Did you do `my_string + "".split()`? If so, you need parens since `+` has a lower precedence than `.`. So like this: `(my_string + "").split()` –  Sep 23 '16 at 13:11
  • @squint The problem was, that I was trying to override the object's property with the string: `myObj.data = myObj.data + '';`. This wasn't possible / the property remained an object. If this is default javascript behavior I will delete my comments. – Martin Schneider Sep 26 '16 at 12:14
  • @MA-Maddin: Object properties are able to be set as non-writeable. Were you able to assign any other values to `myObj.data`? –  Sep 26 '16 at 13:59
93

maybe

string = document.location.href;
arrayOfStrings = string.toString().split('/');

assuming you want the current url

dstarh
  • 4,976
  • 5
  • 36
  • 68
chepe263
  • 2,774
  • 22
  • 38
14

run this

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

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

Matt
  • 41,216
  • 30
  • 109
  • 147
dstarh
  • 4,976
  • 5
  • 36
  • 68
  • Thank you. I didn't realized I converted my var from string to object. Your solution gave me an idea to check back my code. – sg552 Nov 16 '16 at 16:53
9

document.location isn't a string.

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

kapa
  • 77,694
  • 21
  • 158
  • 175
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

In clausule if, use (). For example:

stringtorray = "xxxx,yyyyy,zzzzz";
if (xxx && (stringtoarray.split(',') + "")) { ...
derloopkat
  • 6,232
  • 16
  • 38
  • 45