Erik Kralj Erik Kralj - 6 months ago 13
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('/');
});

</script>


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?

Answer

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.