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

JavascriptJquerySplit

Javascript Problem Overview


Why am I getting...

> Uncaught TypeError: string.split is not a function

...when I run...

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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

maybe

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

assuming you want the current url

Solution 3 - Javascript

run this

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

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

Solution 4 - Javascript

document.location isn't a string.

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

Solution 5 - Javascript

In clausule if, use (). For example:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionerikvimzView Question on Stackoverflow
Solution 1 - Javascriptuser1106925View Answer on Stackoverflow
Solution 2 - Javascriptchepe263View Answer on Stackoverflow
Solution 3 - JavascriptdstarhView Answer on Stackoverflow
Solution 4 - JavascriptDenys SéguretView Answer on Stackoverflow
Solution 5 - JavascriptJonatas AstroPtView Answer on Stackoverflow