Converting a String to an Array

Accessing a string as an array is unsafe. For example, when accessing a string as an array, you might have seen code like this:
   var str = "HELLO WORLD";
   str[0]; 
This will return H
Accessing a string as an array is unsafe and unpredictable because:
  • it does not work in all browsers (not in IE5, IE6, IE7)
  • it makes strings look like arrays (but they are not)
  • str[0] = "H" does not give an error (but it does not work either)
If you want to read a string as an array, convert it to an array first. A string can be converted to an array with the split() method:
   var txt = "a,b,c,d,e";  <== String
   txt.split(",");  <== Split on commas (which will not be counted)
   txt.split(" ");  <== Split on spaces (which will not be counted)
   txt.split("|");  <== Split on pipe (which will not be counted)
If the separator -- the "( )" part -- is omitted, the returned array will contain the whole string in index [0]. If the separator is "", the returned array will be an array of single characters:
   var txt = "Hello";  <== String
   txt.split("");  <== Split in characters

The example that was posted for this one did not make any sense to me. No matter how I looked at it, I just couldn't get it. You can see it on the next webpage...



HTML file: Displayed by browser:
<body>
<p>Click "Try it" to display the first array element, after a string split:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
    var str = "a,b,c,d,e,f";
    var arr = str.split(",");
    document.getElementById("demo").innerHTML = arr[2];
}
</script>
</body>

Click "Try it" to display the third array element, after a string split:


BackTable of ContentsNext