Vanilla JavaScript Trim White Space

— 2 minute read

permalink

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 permalink

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 permalink

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 permalink

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 permalink

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! permalink

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