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 are going to 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 delete whitespace at the end

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

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

See the code exmples 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 ๐Ÿ“–

TypeORM viewEntity

30 Mar, 2022 ยท 5 min read

TypeORM viewEntity

The Record Utility Type in TypeScript

12 Mar, 2022 ยท 3 min read

The Record Utility Type in TypeScript

Join 1372 devs and subscribe to my newsletter