Removing Whitespace From Strings in JavaScript
- 1 minute read
With a bit of help from JavaScript’s built-in RegEx features, this one-liner will remove all the whitespace from a given string:
const string = `This is an example string.`;
string.replace(/\s/g, ``);
Removing just the space character
If you just want to remove the space character and not all whitespace, this snippet will do the trick:
const string = `This is an example string.`;
string.replace(/ /g, ``);
Keep in mind, it won’t remove consecutive spaces or tabs.
For example, "Example string"
will become "Examplestring"
.
However, "Example string"
(with two spaces) will become "Example string"
(with one space).
Trimming trailing whitespace
If you just want to remove the trailing whitespace at the beginning and end of a string (if any), the trim()
function is what you’re looking for:
const string = ` Test `;
const trimmedString = string.trim();
In this example, " Test "
will become "Test"
.
Conclusion
There’s even more ways you can go about doing this, but I personally prefer the RegEx-based solutions.
Thanks for reading, and I hope this helped you!