What causes 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, the following error appears in the Firebug console:

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

What is the reason for this error?

+53
javascript jquery split
Apr 13 2018-12-18T00:
source share
4 answers

Change it ...

 var string = document.location; 

to that...

 var string = document.location + ''; 

This is because document.location is a Location object. By default .toString() returns the location in string form, so concatenation will cause this.




You can also use document.URL to get a string.

+117
Apr 13 2018-12-18T00:
source share

perhaps

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

Assuming you need the current URL

+39
Apr 13 '12 at 18:05
source share

run it

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

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

+6
Apr 13 2018-12-12T00:
source share

document.location not a string.

You might want to use document.location.href or document.location.pathname .

+2
Apr 13 2018-12-18T00:
source share



All Articles