What Is Causing the Error `String. Split Is Not a Function`?

What Is Causing the Error `String. Split Is Not a Function`?

Why am I getting...

Uncaught TypeError: string.split is not a function

...when I run...

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

5 Answers

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.

7

maybe

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

assuming you want the current url

run this

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

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

1

document.location isn't a string.

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

1

In clausule if, use (). For example:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.