1

I've always thought that if you want to access the nth character in a string called str, then you have to do something like str.charAt(n). Today I was making a little dummy test page and by mistake, I accessed it with str[n] and to my surprise, it returned me the nth character of the string. I threw up this little purpose built page to exhibit this unexpected (to me) behaviour:

<!doctype html>
<html>
<body>
    <script>
        var str = "ABCDEFGH";
        if (str[4] === str.charAt(4)) alert("strings can be indexed directly as if they're arrays");
        var str2 = new String("ABCDEFGH");
        if (str2[4] === str2.charAt(4)) alert("even if they're declared as object type String");
    </script>
</body>
</html>

It wasn't always like this, was it?

dfsq
  • 187,712
  • 24
  • 229
  • 250
Dee2000
  • 1,621
  • 2
  • 18
  • 21

3 Answers3

4

There are two ways to access an individual character in a string. The first is the charAt method:

return 'cat'.charAt(1); // returns "a"

The other way is to treat the string as an array-like object, where individual characters correspond to a numerical index:

return 'cat'[1]; // returns "a"

Array-like character access (the second way above) is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String

deceze
  • 491,798
  • 79
  • 706
  • 853
3

No, that was not always possible.

If you run your code in an old enough browser, IE 7 for example, it won't be able to access the string like that. On those older engines, you'd have to use .charAt(index) instead.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
Guffa
  • 666,277
  • 106
  • 705
  • 986
2

As long as I can remember, but:

Array-like character access [...] is not part of ECMAScript 3. It is a JavaScript and ECMAScript 5 feature.

(...and not supported in all browsers) See here.

marsze
  • 13,389
  • 5
  • 38
  • 53