Subscribe

Vanilla JavaScript Trim White Space

✍️

Today we are exploring the JavaScript trim methods in order to remove whitespace from text.

13 May, 2020 · 2 min read

Let's dive into the JavaScript methods for removing white space from a string.

To trim the whitespace, we will use the trim, trimStart, and trimEnd methods in Vanilla JavaScript.

Trim whitespace at the beginning and end

The trim() method is an easy way to remove white space from the beginning and end of a string. After the trimming, it will return a new string.

const quote = "  Gotta Catch 'Em All.      ";
console.log(quote.trim());
// "Gotta Catch 'Em All."

Super simple. As you can see, we removed all trailing and ending whitespace.

Remove white space from the beginning

The trimStart method removes whitespace from the beginning of a string only.

const quote = "  Gotta Catch 'Em All.      ";
console.log(quote.trimStart());
// "Gotta Catch 'Em All.      "

Vanilla JavaScript deletes whitespace at the end

Yes, you guessed it right. The trimEnd method will delete the extra whitespace at the strings ending.

const quote = "  Gotta Catch 'Em All.      ";
console.log(quote.trimEnd());
// "  Gotta Catch 'Em All."

See the code examples in this Codepen

Feel free to play around with this Codepen.

See the Pen Vanilla JavaScript Trim White Space by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 1980 devs and subscribe to my newsletter