JavaScript access string chars as array

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFranciscView Question on Stackoverflow
Solution 1 - JavascriptTim DownView Answer on Stackoverflow
Solution 2 - JavascriptSaulView Answer on Stackoverflow
Solution 3 - JavascriptJamesView Answer on Stackoverflow
Solution 4 - JavascriptEric BishardView Answer on Stackoverflow