Emmanuel Akinfulubi

JavaScriptBasic

Trim whitespace from form input in JavaScript

Beginner · 3 min read

People rarely type exactly what you expect. A search box gets a space before the word, a newline after it from pressing Enter, or invisible characters pasted from a web page. If you compare that text with 'Yaba' straight away, the match fails and nobody can see why. Trimming the input first is one of the simplest fixes in web development.

In this tutorial you will clean up text from a form field with trim, trimStart and trimEnd, and find out which kinds of invisible characters they remove and which they leave behind. You need to know what a string is and how if works.

What whitespace is

Whitespace is any character that shows up as empty space: an ordinary space, a tab, a newline. In JavaScript you can write some of them with a backslash code inside a string:

  • '\n' is a newline.
  • '\t' is a tab.
  • '\u00a0' is a non-breaking space, a space that stops a line from wrapping. Web pages use it a lot, so it often arrives when someone copies and pastes.
  • '\u200b' is a zero-width space. It takes up no room at all, so you can't see it on screen.

Seeing what is really in a string

Invisible characters are hard to debug because console.log doesn't show them. Two tricks help. JSON.stringify(text) prints the string with quotes and shows a newline as \n. And text.length counts every character, visible or not.

JavaScript

console.log(JSON.stringify(' hi\n')); // " hi\n"
console.log(' hi\n'.length);          // 4

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

104 trim, and the whitespace a form field brings

easy

Clean up what someone typed into a search box: leading spaces, a trailing newline, a non-breaking space pasted from a web page, and a zero-width space. Use trim, trimStart and trimEnd, and find out which of those four trim actually removes.

Stuck? Three hints, smallest first
  1. 1. Tabs, newlines and non-breaking spaces all count as whitespace.
  2. 2. A zero-width space is not whitespace, so nothing trims it.
  3. 3. trim touches the two ends only, never the middle.

Step 1: trim both ends

Step 1

const typed = '  Ikeja City Mall \n';
console.log(JSON.stringify(typed.trim())); // "Ikeja City Mall"

trim() removes whitespace from the start and the end of the string: the two spaces in front, and the space and newline behind. Like every string method, it returns a new string and leaves typed unchanged.

Step 2: one end at a time

Sometimes you only want one side cleaned:

Step 2

const typed = '  Ikeja City Mall \n';
console.log(JSON.stringify(typed.trimStart())); // "Ikeja City Mall \n"
console.log(JSON.stringify(typed.trimEnd()));   // "  Ikeja City Mall"

trimStart cleans the start only, trimEnd the end only. Notice that the spaces inside Ikeja City Mall are never touched by any of the three.

JavaScript

console.log(JSON.stringify('  two  words  '.trim())); // "two  words"

The double space between the words survives. trim only works on the two ends.

Step 3: a pasted non-breaking space

Step 3

const pasted = '\u00a0Yaba\u00a0';
console.log(pasted === 'Yaba');        // false
console.log(pasted.trim() === 'Yaba'); // true

The non-breaking space looks like a normal space but isn't equal to ' ', so the first comparison fails. trim counts it as whitespace and removes it, so after trimming the match works.

Step 4: the character trim can't see

Step 4

const invisible = 'Yaba\u200b';
console.log(invisible.trim() === invisible); // true
console.log(invisible.trim().length);        // 5

A zero-width space isn't whitespace. It is a formatting character, so trim leaves it alone. The string still prints as Yaba but has length 5, and it will never equal 'Yaba'. When text looks right but won't match, check its length. That is how you catch this one.

Step 5: a field of only spaces

This is the case that causes real bugs:

Step 5

const field = '   ';
console.log(field ? 'truthy' : 'falsy');        // truthy
console.log(field.trim() ? 'truthy' : 'falsy'); // falsy

A string with spaces in it isn't empty, so if (field) treats it as filled in. After trim() it becomes '', and an empty string counts as false. So the rule for form fields is: trim first, then check.

The full solution

The answer panel trims the search text all three ways, then tries the pasted non-breaking space, the zero-width space and the field of only spaces. Press Run to see the output and the checks.

The answer

const typed = '  Ikeja City Mall \n';
const pasted = '\u00a0Yaba\u00a0';        // non-breaking spaces, from a web page
const invisible = 'Yaba\u200b';           // a zero-width space, from anywhere
console.log(JSON.stringify(typed.trim()));
console.log('zero-width space still there:', invisible.length, 'characters for 4 letters');

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('trim takes both ends off', typed.trim(), 'Ikeja City Mall');
test('trimStart leaves the tail alone', typed.trimStart(), 'Ikeja City Mall \n');
test('trimEnd leaves the head alone', typed.trimEnd(), '  Ikeja City Mall');
test('the middle is never touched', '  two  words  '.trim(), 'two  words');
test('a non-breaking space is whitespace and goes', pasted.trim(), 'Yaba');
test('a zero-width space is not, and stays', invisible.trim(), invisible);
test('which is why the length gives it away', invisible.trim().length, 5);
test('a field of only spaces trims to empty', '   '.trim(), '');
test('but is truthy before you trim it, so trim then test', ['   ' ? 'truthy' : 'falsy', '   '.trim() ? 'truthy' : 'falsy'], ['truthy', 'falsy']);

The last assertion is the one that reaches production. ' ' is a non-empty string, so if (value) is true and a required field made entirely of spaces sails through. Trim first, then ask (exercise 116 builds that check properly).

trim is generous about what whitespace means — spaces, tabs, newlines, and the non-breaking space that arrives whenever text is pasted from a web page, which is invisible and not equal to ' '. It is not generous enough for a zero-width space, which is a formatting character rather than whitespace, so 'Yaba\u200b' trims to itself and compares unequal to 'Yaba' for reasons nobody can see on screen. When a string looks right but will not match, print its length. And trim only works on the ends: collapsing runs inside the text needs replace(/\s+/g, ' ').

Common mistakes

  • Checking a field before trimming it. ' ' passes if (value). Trim, then test.
  • Expecting trim to tidy the middle. It only touches the ends. To squash runs of spaces inside the text, use text.replace(/\s+/g, ' ').
  • Forgetting to keep the result. typed.trim(); on its own line does nothing useful. Write const clean = typed.trim();.

Try it yourself

  1. Write isBlank(text) that returns true for '', ' ' and '\n\t', and false for ' a '.
  2. Clean ' Ikeja City Mall ' into 'Ikeja City Mall', with single spaces between the words.
  3. Write removeZeroWidth(text) that deletes every '\u200b' with replaceAll, and check that 'Yaba\u200b' then equals 'Yaba'.

Keep practising

Newsletter

New writing, when it lands.

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