How to Strip Whitespace from JavaScript Strings
Table of Contents
When you have strings in JavaScript, sometimes those strings will come with whitespace, which is just extra characters like spaces, tabs, and newlines.
When you want to get rid of these, you will need to strip them out.
In this post, we will look at how to strip whitespace from strings.
Strip Whitespace from Strings
When you want to strip whitespace from a string, you can use the trim()
method. This method lives natively on the String
object.
The trim()
method will remove all whitespace from the beginning and end of the string.
Let's see an example of this.
JAVASCRIPTconst string = " Hello World! ";
string.trim(); // "Hello World!"
Keep in mind that the trim()
method will only remove whitespace from the beginning and end of the string. It will not remove whitespace from the middle of the string.
JAVASCRIPTconst string = " Hello World! ";
string.trim(); // "Hello World!"
If you want to remove all spaces you can split the string into an array and then join it back together.
JAVASCRIPTconst string = " Hello World! ";
string.split(" ").join(""); // "HelloWorld!"
Another way you can remove all spaces is to use the replaceAll()
method.
JAVASCRIPTconst string = " Hello World! ";
string.replaceAll(" ", ""); // "HelloWorld!"
Conclusion
In this post, we've taken a look at all the ways you can strip whitespace from strings.
You have several options, including using the trim()
method, splitting the string into an array and then joining it back together, and the replaceAll()
method.
Hopefully, you've found this post useful. Happy coding!
- Getting Started with Solid
- Getting Started with Svelte
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- Best Visual Studio Code Extensions for 2022
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API