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
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. ";
console.log(quote.trim());
// "Gotta Catch 'Em All."
Super simple as you can see, we removed all trailing and ending whitespace.
Vanilla JavaScript trimStart() method
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. ";
console.log(quote.trimStart());
// "Gotta Catch 'Em All. "
Vanilla JavaScript trimEnd() method
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. ";
console.log(quote.trimEnd());
// " 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!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
Top comments (0)