Skip to content

Trim Methods

trim() returns a copy of a string with the whitespace removed from both ends. trimStart() removes it from the start only, and trimEnd() from the end only. Whitespace inside the string is left alone. The main use is cleaning text typed into a form, where a stray space or a pasted line break would otherwise make two equal values look different.

JSON.stringify() is used here to make the tab and line break visible.

const raw = '\t Hello world \n';
console.log(JSON.stringify(raw.trim()));
console.log(JSON.stringify(raw.trimStart()));
console.log(JSON.stringify(raw.trimEnd()));
console.log(JSON.stringify(raw));

This prints:

"Hello world"
"Hello world \n"
"\t Hello world"
"\t Hello world \n"

The last line shows that raw itself is unchanged, because strings are immutable.

The trim methods remove the characters JavaScript treats as whitespace and line terminators. These include the space, the tab, the line feed and carriage return, the no-break space (U+00A0), the byte order mark (U+FEFF) and the other space characters in Unicode. The zero-width space (U+200B) is not whitespace in this sense, so it survives trimming, and it often arrives in text pasted from web pages.

const noBreak = ' Price ';
const byteOrderMark = 'name';
const zeroWidth = '​code​';
console.log(noBreak.trim().length);
console.log(byteOrderMark.trim().length);
console.log(zeroWidth.trim().length);
console.log(zeroWidth.replace(/​/g, '').length);

This prints:

5
4
6
4

The byte order mark matters when reading the first line of a file saved by some editors, because a heading such as name would otherwise fail to match.

To collapse runs of spaces inside a string as well, follow trim() with a replace() that matches any run of whitespace.

const messy = ' too many spaces ';
console.log(JSON.stringify(messy.trim()));
console.log(JSON.stringify(messy.trim().replace(/\s+/g, ' ')));

This prints:

"too many spaces"
"too many spaces"

A field holding only spaces is not an empty string, so it is truthy. Trimming before the check catches it.

const answer = ' ';
if (answer.trim() === '') {
console.log('Please enter a name');
}
console.log(Boolean(answer), Boolean(answer.trim()));

This prints:

Please enter a name
true false

trimLeft() and trimRight() are older names for the same methods. They are kept for compatibility, and are in fact the same functions.

console.log(String.prototype.trimLeft === String.prototype.trimStart);
console.log(String.prototype.trimRight === String.prototype.trimEnd);
console.log(String.prototype.trimLeft.name);

This prints:

true
true
trimStart

Use trimStart() and trimEnd() in new code, since they match padStart() and padEnd() and read correctly in right-to-left languages, where the start of a string is on the right.

Steve Griffith covers this topic in his video JS String trimming methods.