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.
The string in JavaScript can be converted into a character array by using the split() and Array. from() functions. Example: html.
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.
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.
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.
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]);
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With