Syntax
str.length
str.charAt(index)
str.at(index)Examples
Length and Character Access
Getting a string's length and accessing individual characters.
const text = "Hello";
console.log(text.length); // 5
console.log(text.charAt(0)); // "H"
console.log(text[1]); // "e" - bracket access also works
console.log(text.charAt(10)); // "" - out of range returns empty stringat() with Negative Indices
Using at() to easily access characters from the end of the string.
const text = "JavaScript";
console.log(text.at(0)); // "J"
console.log(text.at(-1)); // "t" - last character
console.log(text.at(-2)); // "p" - second to last
// Compare with charAt(), which has no negative index support
console.log(text.charAt(text.length - 1)); // "t" - more verbose equivalentBest practices
- Use at(-1) instead of str[str.length - 1] for cleaner access to the last character
- Remember strings are immutable - "changing" a character actually means creating an entirely new string
- Use bracket notation (str[0]) or charAt() interchangeably for simple positive-index access - both work identically for valid indices
- Check .length before accessing indices in a loop to avoid undefined results from out-of-range access
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification