← coderrocketfuel.com

How to Remove Whitespace From a String in Node.js

How to remove all the whitespace from a string in Node.js?

You can remove the whitespace in a string by using a string.replace(/\s/g, "") regular expression or a string.split(" ").join("") method.

We'll go over how to use both of those in this article.

Let's get started!

Table of Contents

Method 1 - Regular Expression

The first way to remove the whitespace from a string is through the means of a regular expression that parses the string and removes any empty spaces it finds.

To demonstrate the regular expression, we'll give it a string with a bunch of spaces in it and see what it spits out.

Here's a code example:

const myString = " /user/directory/ New Document Name.txt"

myString.replace(/\s/g, "")
// returns "/user/directory/NewDocumentName.txt"

We use the replace() function on our string to remove each space the regular expression finds. Notice that the new string returned by the method doesn't have any spaces.

Pretty cool, right? We have one more method to cover in the next section.

Method 2 - Split() & Join()

The second and last method we'll cover puts to use a combination of .split() and .join() functions. Although the result will be a string with the empty spaces removed and therefore the same as the previous method, the approach is a little different.

Here's what the code looks like:

const myString = " /user/directory/ New Document Name.txt"

myString.split(" ").join("")
// returns "/user/directory/NewDocumentName.txt"

Notice that the result is the same as the last method where a string with no spaces is returned.

The split() method splits a string into an array of strings by separating the original string into substrings. It uses a specified separator to determine where to make each split. In this case, it uses the space we gave it as an argument.

Then, the join() method takes each string in the array created by split() and returns a new string with the commas in the array removed.

The result of those two functions manipulating the original myString variable is a string with all the empty whitespaces removed.