164

Why am I getting...

Uncaught TypeError: string.split is not a function

...when I run...

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

2
  • 3
    document.location is an object. Try: var string=document.location.href Commented Apr 13, 2012 at 18:04
  • I have just been trying to do exactly this Commented Sep 22, 2023 at 11:48

5 Answers 5

278

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Would not it be cleaner to call toString() instead of hacky concatenation?
@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.
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.
the + '' method doesn't change anything for me in Chrome Browser but toString() does.
@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()
|
95

maybe

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

assuming you want the current url

Comments

14

run this

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

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

1 Comment

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.
9

document.location isn't a string.

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

1 Comment

lol. 4 answers (at least) at the same time. I shouldn't look at the newest questions on SO :)
1

In clausule if, use (). For example:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.