The following example displays characters at different locations in the string "Brave new world"
:
const anyString = "Brave new world";
console.log(`The character at index 0 is '${anyString.charAt()}'`);
console.log(`The character at index 0 is '${anyString.charAt(0)}'`);
console.log(`The character at index 1 is '${anyString.charAt(1)}'`);
console.log(`The character at index 2 is '${anyString.charAt(2)}'`);
console.log(`The character at index 3 is '${anyString.charAt(3)}'`);
console.log(`The character at index 4 is '${anyString.charAt(4)}'`);
console.log(`The character at index 999 is '${anyString.charAt(999)}'`);
These lines display the following:
The character at index 0 is 'B'
The character at index 0 is 'B'
The character at index 1 is 'r'
The character at index 2 is 'a'
The character at index 3 is 'v'
The character at index 4 is 'e'
The character at index 999 is ''
charAt()
may return lone surrogates, which are not valid Unicode characters.
const str = "𠮷𠮾";
console.log(str.charAt(0));
console.log(str.charAt(1));
To get the full Unicode code point at the given index, use an indexing method that splits by Unicode code points, such as String.prototype.codePointAt()
and spreading strings into an array of Unicode code points.
const str = "𠮷𠮾";
console.log(String.fromCodePoint(str.codePointAt(0)));
console.log([...str][0]);
Note: Avoid re-implementing the solutions above using charAt()
. The detection of lone surrogates and their pairing is complex, and built-in APIs may be more performant as they directly use the internal representation of the string. Install a polyfill for the APIs mentioned above if necessary.