Vanilla JavaScript Trim White Space

— 2 minute read


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

We are going to use the trim, trimStart, and trimEnd methods in Vanilla JavaScript.

Vanilla JavaScript trim() method permalink

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

var quote = "  Gotta Catch 'Em All.      ";
// "Gotta Catch 'Em All."

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

Vanilla JavaScript trimStart() method permalink

The trimStart method is the same as the trim method above, but it will only trim the beginning of the string.

var quote = "  Gotta Catch 'Em All.      ";
// "Gotta Catch 'Em All. "

Vanilla JavaScript trimEnd() method permalink

Yes, you guessed it right, this one is again the same but will trim only the end of our string.

var quote = "  Gotta Catch 'Em All.      ";
// " Gotta Catch 'Em All."

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