The JavaScript `String.trim()` method explained

technoph1le

Technophile

Posted on December 24, 2022

The JavaScript `String.trim()` method explained

In JavaScript, the trim() method removes whitespace from both ends of a string. It returns a new copy of the string with whitespace removed.

Table of Contents


How it works

Syntax

string.trim();
Enter fullscreen mode Exit fullscreen mode

Example:

const string = "  Hello World!  ";
console.log(string.trim()); // "Hello World!"
Enter fullscreen mode Exit fullscreen mode

Parameters

The trim() method does not take any parameters.

Return value

A new string with whitespace removed from both ends while leaving the original string unchanged.


Alternative methods

If you want to remove whitespace either from the beginning or the end of a string, you can use the trimStart() or trimEnd() methods.

const string = "  Hello World!  ";
console.log(string.trimStart());
// "Hello World!  "

console.log(string.trimEnd());
// "  Hello World!"

console.log(string.trim());
// "Hello World!"

console.log(string);
// "  Hello World!  "
Enter fullscreen mode Exit fullscreen mode

Alternatively, it's possible to use the regular expression to achieve the same result.

const string = "  Hello World!  ";
console.log(string.replace(/^\s+|\s+$/g, ""));
// "Hello World!"
Enter fullscreen mode Exit fullscreen mode

If you're really curious about how this regex works, check out this Stack Overflow answer.


More examples

The trim() method can come in handy when you need to remove unwanted whitespace from a string in user input or search queries.

See the Pen
The JavaScript trim() explained
by Technophile (@dostonnabotov)
on CodePen.


Browser compatibility

Since the trim() method is part of the ECMAScript5 (ES5 - JavaScript 2009) standard, it's well supported in all browsers.


Conclusion

I hope this article helped you understand how the trim() method works. Regarding any questions or suggestions, feel free to leave a comment below. Thanks for reading! 🙂


Resources

đź’– đź’Ş đź™… đźš©
technoph1le
Technophile

Posted on December 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related