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