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
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