Emmanuel Akinfulubi

JavaScriptBasic

Validate text length (and count emoji) in JavaScript

Beginner ยท 3 min read

"Your note must be between 3 and 20 characters." You've seen messages like that on usernames, bios, comments and delivery notes. Checking a length is quick to write, but there are two traps: getting the edges of the range wrong, and miscounting characters like emoji.

In this tutorial you will write a function called lengthOk that checks a text is between a minimum and maximum length, counting the way a person would. You need to know what strings and functions are, and how comparisons like >= work.

Inclusive bounds

"Between 3 and 20, inclusive" means 3 is allowed and 20 is allowed. In code:

JavaScript

const n = 20;
console.log(n >= 3 && n <= 20); // true

>= means "greater than or equal to" and <= means "less than or equal to". If you accidentally write < instead of <=, everything still works for a 10-character note. Only someone who types exactly 20 characters finds the bug. That's why you always test the edges: the minimum, one below it, the maximum and one above it.

What .length really counts

Inside JavaScript, text is stored as small pieces called code units. Ordinary letters take one each. Many emoji take two. .length counts code units, not characters:

JavaScript

console.log('a'.length);         // 1
console.log('\u{1F68C}'.length); // 2

'\u{1F68C}' is the bus emoji written as a code. Spreading a string with [...text] splits it into real characters instead (each one is called a code point), so [...text].length counts what a person sees:

JavaScript

console.log([...'\u{1F68C}'].length); // 1

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

117 Is the text long enough, and what counts as a character

easy

Check that a note is between 3 and 20 characters, inclusive. Then count a note containing an emoji both ways and decide which count the user would agree with.

Stuck? Three hints, smallest first
  1. 1. Inclusive bounds mean >= and <=; getting one wrong is invisible until someone hits the edge.
  2. 2. Trim before measuring, or trailing spaces buy length.
  3. 3. .length counts UTF-16 units; [...text].length counts code points.

Step 1: a first version

Step 1

function lengthOk(text, min, max) {
  const n = String(text).length;
  return n >= min && n <= max;
}
console.log(lengthOk('abc', 3, 20)); // true
console.log(lengthOk('ab', 3, 20));  // false

It works for ordinary text. Now test the edges and the tricky inputs.

Step 2: trailing spaces buy length

Step 2

function lengthOk(text, min, max) {
  const n = String(text).length;
  return n >= min && n <= max;
}
console.log(lengthOk('ab ', 3, 3)); // true

'ab ' is two letters and a space, and it passes a 3-character minimum. Spaces at the ends shouldn't count, so trim first.

Step 3: emoji count double

Step 3

const note = 'Yaba \u{1F68C}';
console.log(note.length);      // 7
console.log([...note].length); // 6
const queue = '\u{1F68C}'.repeat(10);
console.log(queue.length);      // 20
console.log([...queue].length); // 10

Yaba, a space and one bus is six characters to anyone reading it, but .length says 7. Ten bus emoji look like twenty. With a limit of 10, a user who typed ten emoji would be told their note is too long, which they'd rightly find baffling.

Step 4: the fixed function

Step 4

function lengthOk(text, min, max) {
  const value = String(text).trim();
  const n = [...value].length;
  return n >= min && n <= max;
}
const queue = '\u{1F68C}'.repeat(10);
console.log(lengthOk('ab ', 3, 3));   // false
console.log(lengthOk('abc  ', 3, 3)); // true
console.log(lengthOk(queue, 1, 10));  // true

trim() removes the spaces at the ends, and [...value].length counts characters instead of code units.

Step 5: test all four edges

Step 5

function lengthOk(text, min, max) {
  const value = String(text).trim();
  const n = [...value].length;
  return n >= min && n <= max;
}
console.log(lengthOk('abc', 3, 20));          // true: exactly the minimum
console.log(lengthOk('ab', 3, 20));           // false: one short
console.log(lengthOk('a'.repeat(20), 3, 20)); // true: exactly the maximum
console.log(lengthOk('a'.repeat(21), 3, 20)); // false: one over

'a'.repeat(20) builds a string of twenty as. These four lines are the tests that catch a < written where <= was meant.

Step 6: closer, but not perfect

Some things that look like one character are made of several code points: many flags, family emoji, and a letter followed by a separate accent mark.

Step 6

console.log([...'e\u0301'].length); // 2

'e\u0301' is an e followed by a combining accent, and it shows as a single รฉ. Spreading counts 2. The unit a person actually sees is called a grapheme, and JavaScript can count those with Intl.Segmenter. Reach for it when you show a live character count to the user. For a simple limit, [...text].length is a big improvement on .length.

The full solution

The answer panel has the finished lengthOk, prints the bus note's two counts, and checks all four edges, trailing spaces, the emoji counts, ten buses against a limit of ten, and a minimum of zero letting an empty note through. Press Run to see the output.

The answer

function lengthOk(text, min, max) {
  const value = String(text).trim();
  const n = [...value].length;
  return n >= min && n <= max;
}
const note = 'Yaba ๐ŸšŒ';
const queue = '๐ŸšŒ'.repeat(10);
console.log(note, 'is', note.length, 'units but', [...note].length, 'characters');

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('exactly the minimum is allowed', lengthOk('abc', 3, 20), true);
test('one short is not', lengthOk('ab', 3, 20), false);
test('exactly the maximum is allowed', lengthOk('a'.repeat(20), 3, 20), true);
test('one over is not', lengthOk('a'.repeat(21), 3, 20), false);
test('trailing spaces do not buy length', [lengthOk('abc  ', 3, 3), lengthOk('ab ', 3, 3)], [true, false]);
test('an emoji is two UTF-16 units but one character', [note.length, [...note].length], [7, 6]);
test('so ten buses look like twenty to .length', [queue.length, [...queue].length], [20, 10]);
test('and a limit of ten accepts them when you count characters', lengthOk(queue, 1, 10), true);
test('a minimum of zero lets an empty field through, which is a different rule', lengthOk('', 0, 5), true);

Also exercise 37, which cut text to a length; here the angle is what a length counts. JavaScript strings are UTF-16, and .length reports storage units, not characters โ€” so an emoji costs 2, and a note of ten bus emojis reports 20 and is rejected by a 20-character limit the user has not reached. Spreading or Array.from iterates code points and gives the count a person would recognise.

Code points are closer, not correct. A flag, a family emoji or an accented letter written as e plus a combining mark is several code points and one visible character, so [...'e\u0301'].length is 2. The genuinely correct unit is the grapheme cluster, which needs Intl.Segmenter; reach for it when the count is shown to a user, as in a character countdown. Note also that the inclusive bounds are asserted at all four edges โ€” min, min - 1, max, max + 1 โ€” because an off-by-one in a range check passes every test that only uses values in the middle.

Common mistakes

  • Writing < for an inclusive maximum. Exactly 20 characters would be refused. Test the edges.
  • Measuring before trimming. Spaces then count toward the minimum.
  • Trusting .length for typed text. Emoji count as two. Use [...text].length.

Try it yourself

  1. Write charsLeft(text, max) that returns how many characters are left, like a tweet counter.
  2. Change lengthOk to return a message: 'too short', 'too long' or ''.
  3. Count the characters in 'e\u0301' with [...new Intl.Segmenter().segment('e\u0301')].length. What do you get?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.