Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript access string chars as array

Tags:

javascript

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.

like image 984
Francisc Avatar asked Oct 29 '10 11:10

Francisc


People also ask

Can you access a string like an array in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions. Example: html.

Can you access a string as an array?

Answer: Yes. Just like arrays can hold other data types like char, int, float, arrays can also hold strings. In this case, the array becomes an array of 'array of characters' as the string can be viewed as a sequence or array of characters.

How do I convert a string to an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

Is string a character array in JavaScript?

A string is the sequence of characters. To solve our problem, we just need to split every character. There can be various ways to make a character array from the string in JavaScript, and some built-in methods can solve our problem.


2 Answers

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]); 
like image 175
Tim Down Avatar answered Sep 30 '22 18:09

Tim Down


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)); 
like image 38
Saul Avatar answered Sep 30 '22 19:09

Saul