Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Nilesh Raut
Nilesh Raut

Posted on • Originally published attechnilesh.com

     

String.charAt() Method in JavaScript

pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
lionelrowe profile image
lionel-rowe
  • Joined
• Edited on• Edited

Square-bracket indexing of code units within a string isn't a "modern alternative" tocharAt, both have been in JS since the beginning. The only difference is square-bracket indexing returnsundefined instead of"" for out-of-bounds indexes.

NeithercharAt nor square-bracket indexing are truly modern alternatives, because neither support non-BMP characters (e.g. most emojis):

'💩'[0]// '\uD83D''💩'.charAt(0)// '\uD83D'
Enter fullscreen modeExit fullscreen mode

You can make a more modern version that works generically on iterables something like this:

functionatIndex(iter,idx){if(idx<0)return[...iter].at(idx)leti=0for(constelementofiter){if(i++===idx)returnelement}}
Enter fullscreen modeExit fullscreen mode

Usage:

console.log(atIndex('💩 abc',0))// 💩console.log(atIndex('abc 💩',-1))// 💩console.log(atIndex(newIntl.Segmenter('th-TH').segment('แปลให้หน่อยได้ไหม'),4,)?.segment,)// ห้
Enter fullscreen modeExit fullscreen mode

Strings are iterated by codepoint, rather than code-unit, so emojis and other non-BMP characters are handled correctly.

The last example uses segments from anIntl.Segmenter as the iterable, so each "character" is a grapheme cluster (closer to the concept of what users of relevant languages would consider to be a "character"). A grapheme cluster can consist of one or more Unicode codepoints.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software engineer @jio , Founder of Nileshblog.tech & Technilesh.com and More.
  • Location
    India
  • Education
    SIT
  • Pronouns
    Nilesh
  • Work
    intern @ YBI , FRT , Almanet , Suven
  • Joined

More fromNilesh Raut

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp