How to Remove White Space from Start or End of a String in JavaScript
Table of Contents
When you're working with strings, you usually don't want to have whitespace at the start or the end of a string.
This can happen when you're working with strings that you don't control and can therefore have characters you don't want.
In this post, we'll learn how to remove whitespace at the start and end of a string in JavaScript.
Using the trim() method
The easiest way to trim whitespace from the start and end of a string is to use the trim()
method. This method is called directly on the string variable and returns the string with the whitespace removed.
JAVASCRIPTconst string = " Hello World! ";
const stripped = string.trim();
console.log(stripped);
BASHHello World!
Using the trimStart() method
When you're only interested in removing the whitespace from the beginning of the string, use the trimStart()
method. It functions exactly like the trim
method except
JAVASCRIPTconst string = " Hello World! ";
const stripped = string.trimStart();
console.log(stripped);
BASHHello World!
Using the trimEnd() method
Alternatively, when you only want to remove whitespace from the end of the string, use the trimEnd()
method. It's the opposite of the trimStart()
method.
JAVASCRIPTconst string = " Hello World! ";
const stripped = string.trimEnd();
console.log(stripped);
BASHHello World!
Conclusion
In this post, we learned how to use the three different methods for removing whitespace from a string.
Your options are to remove them from both the start and end, just the start, or just the end.
Hopefully, this post has been useful to you. Thanks for reading!
- Getting Started with Solid
- Best Visual Studio Code Extensions for 2022
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js