HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptCritical

How to get first character of string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howcharacterstringgetfirst

Problem

I have a string, and I need to get its first character.



var x = 'somestring';
alert(x[0]); //in ie7 returns undefined




How can I fix my code?

Solution

charAt can give wrong results for Unicode. Use Array.from:
Array.from('some string')[0];


[Note: The post originally recommended .charAt(). It was updated in June 2022 to recommend Array.from(). The discussion in the comments can be confusing without that piece of info.]

Context

Stack Overflow Q#3427132, score: 1317

Revisions (0)

No revisions yet.