views:

36

answers:

2

Hello!

Is it ok to do this:

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

Or should it be done with either charAt(0) or substr(0,1)? By "is it ok" I mean will it work on most browsers, is there a best practice recommandation that says otherwise etc.

Thank you.

+3  A: 

Using charAt is probably the best idea since it conveys the intent of your code most accurately. Calling substr for a single character is definitely an overkill.

alert(myString.charAt(0));
Saul
Thank you, Saul.
Francisc
+4  A: 

Accessing characters as numeric properties of a string is non-standard and doesn't work in all browsers (for example, it doesn't work in IE 6 or 7). You should use myString.charAt(0) instead. Alternatively, if you're going to be accessing a lot of characters in the string then you can turn a string into an array of characters using its split() method:

var myString = "Hello!";
var strChars = myString.split("");
alert(strChars[0]);
Tim Down
just to add a link/reference for the non-standard comment, see (under Character access): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String
davin
@davin: Thanks. I've now linked to that section in my answer.
Tim Down
Thanks, Tim. Just wanted to add that it does work in IE8. Not sure about others.
Francisc
@Francisc: Ah, OK, thanks. I tested on IE 7. I've updated my answer.
Tim Down
@Francisc: Are you sure accessing characters as numeric properties of a string works in IE 8? It doesn't seem to.
Tim Down
Hey! Yup: `var myStr="JavaScript";alert(myStr[4]);` will show "S". Just gave it another test.
Francisc