Erik Kralj Erik Kralj - 4 months ago 11x
jQuery Question

What is causing the following error: "string.split is not a function" in javascript?

I have the following JavaScript code shown below:

<script type="text/javascript">

$(document).ready(function() {
var string = document.location;
var string2 = string.split('/');


When I run this code, I get the following error showing in the Firebug console:

string.split is not a function
var string2 = string.split('/');

What is the cause for this error?


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.