Emmanuel Akinfulubi

JavaScriptString

trim, trimStart and trimEnd in JavaScript

Beginner · 3 min read

People type spaces they don't mean to. They paste an email address with a space on the end, tap the space bar before their name, or copy a line that ends with a hidden line break. If you save that text as it is, 'ada@example.com ' won't match 'ada@example.com', and a field holding only spaces looks filled in when it is empty.

JavaScript has three methods to clean this up: trim removes extra spaces from both ends, trimStart from the front only, and trimEnd from the back only. In this tutorial you will use all three on ' Lagos ', see what counts as a space, and learn the standard check for a blank form field. You only need to know what a string is.

What whitespace means

Whitespace is any character that shows up as empty space rather than a mark on the page. It includes more than the space bar:

  • the ordinary space, ' ',
  • a tab, written '\t' in code,
  • a line break, written '\n',
  • a non-breaking space, a special space that web pages and word processors use to keep two words on the same line. In code it is written '\u00a0'.

All of them look the same on screen, which is exactly why they cause bugs. The trim methods remove all of them.

The methods return new strings

Strings in JavaScript can't be changed once they are made. So trim doesn't change your string; it gives you a new, cleaned-up one. Store it if you want to keep it.

Here is the exercise. Try it on your own first if you like, or read on and we will build it step by step.

18 Trim whitespace, from one end or both

easy

Remove the whitespace around ' Lagos ', then remove it from only the front, then only the back.

Stuck? Three hints, smallest first
  1. 1. trim, trimStart and trimEnd all return new strings.
  2. 2. None of them touches whitespace in the middle.
  3. 3. Whitespace here means more than the space character: tabs, newlines and a non-breaking space all count.

Step 1: trim both ends

Step 1

const messy = '   Lagos   ';
console.log(JSON.stringify(messy.trim())); // "Lagos"

Three spaces come off the front and three off the back. JSON.stringify puts quotes around the result when it is printed, so you can see exactly where the spaces are, or aren't.

Step 2: trim one end only

Step 2

const messy = '   Lagos   ';
console.log(JSON.stringify(messy.trimStart())); // "Lagos   "
console.log(JSON.stringify(messy.trimEnd()));   // "   Lagos"

trimStart cleans the front and keeps the back. trimEnd does the opposite. You'd use trimEnd on lines of text where the spaces at the front are indentation you want to keep.

Step 3: the middle is never touched

Step 3

console.log(JSON.stringify('  a  b  '.trim())); // "a  b"

Only the ends are cleaned. The two spaces between a and b stay. Squashing spaces inside the text is a different job, done with replace.

Step 4: tabs, line breaks and the hidden space

Step 4

console.log(JSON.stringify('\t\nLagos\n'.trim()));  // "Lagos"
console.log(JSON.stringify('\u00a0Lagos'.trim()));  // "Lagos"
console.log('\u00a0' === ' ');                      // false

The tab and line breaks go, and so does the non-breaking space. The last line shows why that matters: a non-breaking space looks like a space but isn't the same character. Code that only removes ordinary spaces, such as replace(/ /g, ''), would leave it behind, and that hidden character would quietly break a comparison.

Step 5: detect a blank field

A form field that holds only spaces should count as empty. Trimming makes that check simple:

Step 5

const field = '   ';
console.log(field === '');               // false
console.log(field.trim() === '');        // true
console.log(field.trim().length === 0);  // true

Comparing the raw value with '' lets three spaces through as if the user had typed something. Trim first, then check.

Step 6: the original stays the same

Step 6

const messy = '   Lagos   ';
const clean = messy.trim();
console.log(JSON.stringify(messy));        // "   Lagos   "
console.log(clean.trim() === clean);       // true

messy still has all its spaces. And trimming a string that is already trimmed changes nothing, so it is safe to call trim more than once.

The full solution

Here is the complete answer: all three methods on the same messy string, with the original printed last to show it hasn't changed. Press Run to see the output.

The answer

const messy = '   Lagos   ';

console.log('trim      :', JSON.stringify(messy.trim()));
console.log('trimStart :', JSON.stringify(messy.trimStart()));
console.log('trimEnd   :', JSON.stringify(messy.trimEnd()));
console.log('the original is untouched:', JSON.stringify(messy));

Output


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

10 checks

test('trim takes whitespace off both ends', messy.trim(), 'Lagos');
test('trimStart takes it off the front only', messy.trimStart(), 'Lagos   ');
test('trimEnd takes it off the back only', messy.trimEnd(), '   Lagos');
test('none of them touch the middle', '  a  b  '.trim(), 'a  b');
test('tabs and newlines count as whitespace', '\t\nLagos\n'.trim(), 'Lagos');
test('a string of only spaces trims to empty', '   '.trim(), '');
test('which is how a blank form field is usually detected', '   '.trim().length === 0, true);
test('a non-breaking space is trimmed too', '\u00a0Lagos'.trim(), 'Lagos');
test('the original is never modified', messy, '   Lagos   ');
test('so trimming twice changes nothing further', messy.trim().trim(), 'Lagos');

value.trim() === '' is the check a form needs. value === '' lets a field containing three spaces through, and users produce those constantly by copying text.

The non-breaking space assertion matters more than it looks. Text pasted from a web page or a word processor is full of U+00A0, which looks exactly like a space and is not the same character. trim removes it; a hand-rolled replace(/ /g, '') does not.

Common mistakes

  • Calling messy.trim() and not storing the result. The original keeps its spaces. Write const clean = messy.trim().
  • Checking a field with value === ''. A field of spaces gets through. Use value.trim() === ''.
  • Removing spaces with replace(/ /g, ''). It misses tabs and non-breaking spaces, and it also deletes the spaces between words.

Try it yourself

  1. Write isBlank(text) that returns true for '', ' ' and '\n', and false for ' a '.
  2. Clean every item in [' Ada ', 'Grace ', ' Alan'] with map.
  3. Take ' line one \n line two ', split it on '\n', and trim only the end of each line.

Keep practising

Newsletter

New writing, when it lands.

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