To get the first character of a string in JavaScript, use str.(0) or [...str][0] (or Array.from(str)[0]) when you want full Unicode character/code-point safety (such as emoji or surrogate pairs) and undefined on empty strings—whereas str.charAt(0) returns "" (an empty string) on empty strings and reads a single UTF-16 code unit (which splits surrogate pairs in half). Avoid str[0] without checking typeof str === "string" and str.length > 0 first if you need explicit error handling or Unicode code-point accuracy.
1. Getting the First Character Safely with Unicode Support ([...str][0] / .at(0))
Validate that source is a string, handle empty strings explicitly, and use code-point iteration ([...source][0]) when full Unicode characters (including emojis or supplementary plane characters) matter:
// Return the first Unicode character of a string, or null if empty
function getFirstCharacter(source, { unicodeCodePoint = true } = {}) {
if (typeof source !== "string") {
throw new TypeError("Expected source to be a string.");
}
if (typeof unicodeCodePoint !== "boolean") {
throw new TypeError("Expected unicodeCodePoint to be a boolean.");
}
if (source.length === 0) {
return null;
}
try {
if (unicodeCodePoint) {
for (const char of source) {
return char;
}
return null;
}
return typeof source.at === "function" ? source.at(0) : source.charAt(0);
} catch (error) {
throw new Error(`Failed to extract first character: ${error.message}`);
}
}
// Example usage:
try {
console.log(getFirstCharacter("JavaScript")); // "J"
console.log(getFirstCharacter("🚀Launch")); // "🚀"
console.log(getFirstCharacter("")); // null
} catch (error) {
console.error(`${error.name}:${error.message}`);
}
- Use
for...of(or[...str][0]) for emoji / surrogate pairs:"🚀"[0]or"🚀".charAt(0)returns an unpaired high surrogate ("\uD83D"), whereasfor...ofyields the full"🚀"character. - Guard empty strings (
source.length === 0): Returningnullor checking explicitly avoids ambiguity between an empty string and a missing value.
2. Comparing .at(0), .charAt(0), .slice(0, 1), and Bracket Indexing
Different string-access methods behave subtly differently on empty strings, negative indices, and surrogate pairs:
// Compare common ways to read the first character of a string
function inspectFirstCharMethods(text) {
if (typeof text !== "string") {
throw new TypeError("Expected text to be a string.");
}
try {
const metrics = new Map([
["bracketIndex", text[0] ?? null],
["charAt", text.charAt(0)],
["atZero", text.at(0) ?? null],
["sliceZeroOne", text.slice(0, 1)],
["firstCodePoint", [...text][0] ?? null]
]);
return metrics;
} catch (error) {
throw new Error(`Failed comparing first-character methods: ${error.message}`);
}
}
// Example usage:
try {
const info = inspectFirstCharMethods("Node.js");
console.log("First code point:", info.get("firstCodePoint")); // "N"
console.log("Slice(0, 1):", info.get("sliceZeroOne")); // "N"
} catch (error) {
console.error(`${error.name}:${error.message}`);
}
charAt(0)always returns a string (""when empty): Useful when you strictly want a string return type rather thanundefined.slice(0, 1)is safe on empty strings ("".slice(0, 1) === ""): Never throws on empty strings, though it slices UTF-16 code units rather than grapheme clusters.
3. Leading Whitespace, Combining Marks, and Locale Considerations
Before taking the first character of user or API text, decide whether leading whitespace or combined diacritics / grapheme clusters should be normalized or preserved:
- Trim leading whitespace only when appropriate (
source.trimStart()):" hello"starts with" "if untrimmed; usesource.trimStart()only when leading spaces should not count as the first character. - Combining characters (
e\u0301vs.é) split across code points:[..."e\u0301"][0]yields"e"without the combining acute accent; useIntl.Segmenter(new Intl.Segmenter(undefined, { granularity: "grapheme" })) if visual grapheme clusters must stay together. - Avoid
substring(0, 1)orsubstr(0, 1)in new code:substr()is legacy, andat(0)/slice(0, 1)/for...ofare clearer and more modern.
