Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  131] [ 6]  / answers: 1 / hits: 60486  / 14 Years ago, fri, october 29, 2010, 12:00:00

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.


More From » javascript

 Answers
126

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

[#95140] Tuesday, October 26, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elmer

Total Points: 432
Total Questions: 96
Total Answers: 107

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
;