JavaScript Trim String

Jan 4, 2021

JavaScript strings have a trim() method that you can use to can use to remove leading and trailing whitespace from a string.

let str = ' hello world ';
str.trim(); // 'hello world'

str = 'hello world ';
str.trim(); // 'hello world'

The trim() method removes all whitespace characters, not just spaces. That includes tabs and newlines.

let str = '\thello world\n';
str.trim(); // 'hello world'

trimStart() and trimEnd()

As of ES2019, JavaScript strings also have trimStart() and trimEnd() methods. The trimStart() function removes all leading whitespace, and trimEnd() removes all trailing whitespace. In other words, str.trimStart().trimEnd() is equivalent to str.trim().

let str = ' hello world ';
str.trimStart(); // 'hello world '
str.trimEnd(); // ' hello world'

However, we do not recommend using trimStart() and trimEnd() without a polyfill. Since trimStart() and trimEnd() are new in ES2019, they are not supported in Node.js before v10.x, and they are not supported in any version of Internet Explorer. We recommend using string replace() method and regular expressions instead.

let str = ' hello world ';
str.replace(/^\s+/, ''); // 'hello world '
str.replace(/\s+$/, ''); // ' hello world'

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Fundamentals Tutorials

×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!