55

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.

4 Answers 4

55

Accessing characters as numeric properties of a string is non-standard prior to ECMAScript 5 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 when your code has to work in non-ECMAScript 5 environments. 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]);
Sign up to request clarification or add additional context in comments.

9 Comments

just to add a link/reference for the non-standard comment, see (under Character access): developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
@davin: Thanks. I've now linked to that section in my answer.
Thanks, Tim. Just wanted to add that it does work in IE8. Not sure about others.
@Francisc: Ah, OK, thanks. I tested on IE 7. I've updated my answer.
@Francisc: Are you sure accessing characters as numeric properties of a string works in IE 8? It doesn't seem to.
|
52

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

1 Comment

This approach fails if the first character in the string is represented by multiple UTF8 code points (emoji, combining characters, etc).
20

2018 answer: Yes it is OK to access strings like arrays.

The syntax is clear and concise. IE6 and IE7 are long gone. I see no reason not to use it.

2 Comments

However: don't get confused into thinking you can use all the Array methods, like reverse and pop, on Strings.
I found you cannot assign into a char. myString[1] = 'u' doesn't change it to "Hullo" (discussed here stackoverflow.com/a/13371244/209288)
8

In ES6 we can use destructuring since a string can be treated as an array:

const [...rest] = 'Hello!';

console.log(rest)
> Array ["H", "e", "l", "l", "o", "!"]

console.log(rest[0])
> "H"

2 Comments

This should be the correct answer, as it's the only method which correctly handles characters that cannot be represented by a single UTF8 code point (combining characters, emoji, etc).
You don't need ES6 to do that. rest = Array.prototype.slice.call("Hello!") will return the same thing and it works in old browsers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.