Array of JavaScript Access Symbols as an Array

Is it possible to do this:

var myString="Hello!"; alert(myString[0]); // shows "H" in an alert window 

Or should it be done either with charAt (0) or with substr (0,1)? By β€œthis is normal,” I mean whether it will work in most browsers, is there a best practice recommendation that says otherwise, etc.

Thank.

+35
javascript
Oct 29 '10 at 11:33
source share
2 answers

Using charAt is perhaps the best idea, since it most accurately conveys the intent of your code. Calling substr for a single character is definitely redundant.

 alert(myString.charAt(0)); 
+35
Oct 29 '10 at 11:35
source share

Access to characters in the form of numeric string properties is non-standard before ECMAScript 5 and does not work in all browsers (for example, it does not work in IE 6 or 7). You should use myString.charAt(0) instead, when your code should work in environments other than ECMAScript 5. Also, if you want to access a large number of characters in a string, you can turn the string into an array of characters using the method split() :

 var myString = "Hello!"; var strChars = myString.split(""); alert(strChars[0]); 
+41
Oct 29 '10 at 11:39 on
source share



All Articles