DEV Community

Nathan
Nathan

Posted on • Originally published at natclark.com

Removing Whitespace From Strings in JavaScript

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, ``);
Enter fullscreen mode Exit fullscreen mode

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, ``);
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)