Check if a value is a single character in JavaScript
Intermediate · 3 min read
Some inputs should hold exactly one character: a grade letter, a separator, a currency sign, a single key from a keyboard game. JavaScript has no special "character" type, so checking for one means checking for a string that is one character long.
In this tutorial you will write that check, and then find out why .length sometimes counts an emoji as two characters. You should know what a string is and what .length does. The rest is explained from zero.
How JavaScript stores text
Inside JavaScript, a string is a list of small 16-bit pieces called code units. .length counts those pieces, not the characters you see.
Most characters fit in one piece: English letters, digits, accented letters like é, and signs like the naira sign ₦. Emoji and some rarer scripts don't. Each of them needs two pieces, called a surrogate pair.
const naira = '\u20A6'; // the naira sign
const emoji = '\u{1F600}'; // a grinning face
console.log('a'.length); // 1
console.log(naira.length); // 1
console.log(emoji.length); // 2
The \u codes are just another way to type those characters. Each character has a number, called its code point, and \u{1F600} means "the character with code point 1F600".
Two ways to split a string
split('') breaks a string into code units. Spreading it with [...text] breaks it into code points, which keeps each emoji whole:
const emoji = '\u{1F600}';
console.log(emoji.split('').length); // 2
console.log([...emoji].length); // 1
Here is the exercise. Have a go on your own if you like, or read on and we will build it together.
9 Is the value a single character?
fairJavaScript has no character type, so "is it a char" means "is it a string of length 1". Then find out why length is the wrong measure.
Stuck? Three hints, smallest first
- 1. Start with
typeof v === ‘string’ && v.length === 1. - 2. An emoji has a
lengthof 2, becauselengthcounts 16-bit units, not characters. - 3. Spreading a string with
[...v]iterates by code point, which is closer to what a person means.
Step 1: a string of length 1
The direct reading of "one character" is "a string whose length is 1":
const isCharByLength = (v) => typeof v === 'string' && v.length === 1;
console.log(isCharByLength('a')); // true
console.log(isCharByLength('ab')); // false
console.log(isCharByLength('')); // false
console.log(isCharByLength(1)); // false
console.log(isCharByLength(['a'])); // false
console.log(isCharByLength('\u20A6')); // true
The typeof part matters. An array like ['a'] also has a length of 1, and without the type check it would pass.
Step 2: the emoji wrong turn
Now try an emoji:
const isCharByLength = (v) => typeof v === 'string' && v.length === 1;
const emoji = '\u{1F600}';
console.log(isCharByLength(emoji)); // false
console.log(emoji.charCodeAt(0)); // 55357
console.log(emoji.codePointAt(0)); // 128512
A person sees one face, but the check says no, because length is 2. charCodeAt(0) reads only the first code unit, which is half the emoji. codePointAt(0) reads the whole character: 128512 is 1F600 written in ordinary decimal numbers.
Step 3: count code points instead
Spread the string and count the pieces:
const isSingleCodePoint = (v) => typeof v === 'string' && [...v].length === 1;
const emoji = '\u{1F600}';
console.log(isSingleCodePoint(emoji)); // true
console.log(isSingleCodePoint('a')); // true
console.log(isSingleCodePoint('\u20A6')); // true
console.log(isSingleCodePoint('ab')); // false
console.log(isSingleCodePoint('')); // false
For plain letters both checks agree. They only disagree on characters that need two code units, and there the code point version matches what a person means.
Step 4: one mark, two code points
There is one more surprise. An accented letter can be written two ways: as one ready-made character, or as a plain e followed by a separate combining accent that sits on top of it. Both look the same on screen:
const isSingleCodePoint = (v) => typeof v === 'string' && [...v].length === 1;
const eAcute = 'e\u0301'; // e plus a combining accent
console.log(eAcute.length); // 2
console.log([...eAcute].length); // 2
console.log(isSingleCodePoint(eAcute)); // false
Even the code point check sees two pieces. The fix is normalize('NFC'), which joins letter and accent into the single ready-made character where one exists:
const isSingleCodePoint = (v) => typeof v === 'string' && [...v].length === 1;
const eAcute = 'e\u0301';
console.log(eAcute.normalize('NFC').length); // 1
console.log(isSingleCodePoint(eAcute.normalize('NFC'))); // true
console.log(eAcute === '\u00E9'); // false
console.log(eAcute.normalize('NFC') === '\u00E9'); // true
The last two lines show why this matters beyond counting: two strings that look identical aren't equal until you normalize them.
The full solution
The panel has both checks and prints the length and code point count for a letter, the naira sign, an emoji and the accented e. Press Run to see them side by side.
// The literal reading: one 16-bit unit.
const isCharByLength = (v) => typeof v === 'string' && v.length === 1;
// What a person means by "one character": one code point.
const isSingleCodePoint = (v) => typeof v === 'string' && [...v].length === 1;
const emoji = '\u{1F600}'; // a grinning face
const naira = '\u20A6'; // the naira sign
const eAcute = 'e\u0301'; // 'e' plus a combining accent
console.log('"a" length:', 'a'.length, ' code points:', [...'a'].length);
console.log('naira length:', naira.length, ' code points:', [...naira].length, ' ->', naira);
console.log('emoji length:', emoji.length, ' code points:', [...emoji].length, ' ->', emoji);
console.log('e+accent len :', eAcute.length, ' code points:', [...eAcute].length, ' ->', eAcute);
console.log('normalised :', eAcute.normalize('NFC').length, '<- NFC combines them into one');
console.log('emoji charCodeAt(0):', emoji.charCodeAt(0), '<- half a character');
console.log('emoji codePointAt(0):', emoji.codePointAt(0), '<- the whole thing');
Output
18 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 18 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('"a" is one character', isCharByLength('a'), true);
test('"ab" is not', isCharByLength('ab'), false);
test('the empty string is not', isCharByLength(''), false);
test('a number is not a character', isCharByLength(1), false);
test('nor is a one-item array', isCharByLength(['a']), false);
test('the naira sign fits in one unit', isCharByLength(naira), true);
test('an emoji does NOT, by length', isCharByLength(emoji), false);
test('because its length is 2', emoji.length, 2);
test('but it is a single code point', isSingleCodePoint(emoji), true);
test('and the two checks disagree on it', isCharByLength(emoji) === isSingleCodePoint(emoji), false);
test('they agree on plain letters', ['a', 'z', 'A'].every((c) => isCharByLength(c) === isSingleCodePoint(c)), true);
test('e plus a combining accent is two code points', [...eAcute].length, 2);
test('so neither check calls it one character', isSingleCodePoint(eAcute), false);
test('until it is normalised', isSingleCodePoint(eAcute.normalize('NFC')), true);
test('charCodeAt gives half the emoji', emoji.charCodeAt(0), 55357);
test('codePointAt gives all of it', emoji.codePointAt(0), 128512);
test('split("") breaks the emoji apart', emoji.split('').length, 2);
test('spreading keeps it whole', [...emoji].length, 1);
length counts UTF-16 units, not characters. Most letters are one unit, so the difference stays invisible until an emoji or a less common script arrives — then '😀'.length is 2 and split('') tears it into two meaningless halves. Use [...v] or Array.from(v) to iterate by code point.
Even that is not the end of it. e plus a combining accent is two code points that display as one mark, which is why the exercise also shows normalize('NFC'). Any input that will be compared or measured should be normalised first, or two strings that look identical will not be equal.
Common mistakes
- Leaving out
typeof v === 'string'. An array like['a']has a length of 1 too. - Splitting with
split(''). It cuts emoji in half. Use[...text]orArray.from(text). - Comparing text without normalizing.
'e\u0301'and'\u00E9'look the same but aren't===. Callnormalize('NFC')on both first.
Try it yourself
- Write
countCharacters(text)that returns the number of code points, and try it on'naira \u20A6 \u{1F600}'. - Find out how many code points the Nigerian flag
'\u{1F1F3}\u{1F1EC}'has. Is it one character to a reader? - Write
firstChar(text)that returns the first whole character, even when it is an emoji.