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.
"Example string" will become
"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
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!