Remove/Replace all Whitespace from a String in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 1, 2024
6 min

banner

# Remove/Replace all Whitespace from a String in JavaScript

Use the String.replace() method to remove all whitespace from a string, e.g. str.replace(/\s/g, '').

The replace() method will remove all whitespace characters from the string by replacing them with empty strings.

index.js
const str = ' A B C D '; // โœ… Remove all whitespace from a string (including spaces, tabs and newline characters) const noWhitespace = str.replace(/\s/g, ''); console.log(noWhitespace); // ๐Ÿ‘‰๏ธ 'ABCD' // โœ… Remove only the spaces from a string const noSpaces = str.replace(/ /g, ''); console.log(noSpaces); // ๐Ÿ‘‰๏ธ 'ABCD'

remove all whitespace from string

The code for this article is available on GitHub

If you need to replace all spaces in a string, specify a replacement string as the second argument to String.replace().

index.js
const str = 'bobby hadz com'; const spacesRelaced = str.replace(/ /g, '+'); console.log(spacesRelaced); // ๐Ÿ‘‰๏ธ bobby+hadz+com

replace all spaces in string

The code sample replaces all whitespace characters with a plus +.

The String.replace() method returns a new string with one, some, or all matches of a regular expression replaced with the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

The first argument we passed to the replace() method is a regular expression.

index.js
const str = ' A B C D '; const noWhitespace = str.replace(/\s/g, ''); console.log(noWhitespace); // ๐Ÿ‘‰๏ธ 'ABCD'

The forward slashes / / mark the beginning and end of the regular expression.

The \s special character matches spaces, tabs and newlines.

We used the g (global) flag to specify that we want to match all occurrences of whitespace characters in the string and not just the first occurrence.
index.js
const str = ' A \n B \t C \n D '; const noWhitespace = str.replace(/\s/g, ''); console.log(noWhitespace); // ๐Ÿ‘‰๏ธ 'ABCD'

The second parameter the replace() method takes is the replacement string.

If you need to remove all spaces from the string, specify an empty string as the replacement.

Conversely, if you need to replace the spaces in the string with a different character, pass the replacement string as the second argument to String.replace().

index.js
const str = 'bobby hadz com'; const spacesRelaced = str.replace(/ /g, '+'); console.log(spacesRelaced); // ๐Ÿ‘‰๏ธ bobby+hadz+com

The code sample replaces all whitespace characters with a plus +.

# Only removing/replacing the spaces from the String

The previous code sample removes all whitespace characters from the string, including spaces, tabs and newline characters.

If you only want to remove the spaces from the string, use the following regular expression.

index.js
const str = ' A B C D '; const noSpaces = str.replace(/ /g, ''); console.log(noSpaces); // ๐Ÿ‘‰๏ธ 'ABCD'

only removing replacing spaces from string

The code for this article is available on GitHub

We only specified a space between the forward slashes that mark the beginning and end of the regular expression.

The g (global) flag is used to remove all occurrences of spaces in the string and not just the first occurrence.

The String.replace() method doesn't change the original string, it returns a new string. Strings are immutable in JavaScript.

# Remove/Replace all Whitespace from a String using replaceAll()

Alternatively, you can use the replaceAll() method.

index.js
const str = ' A B C D '; const noWhitespace = str.replaceAll(/\s/g, ''); console.log(noWhitespace); // ๐Ÿ‘‰๏ธ 'ABCD'

The String.replaceAll() method returns a new string with all matches of a pattern replaced by the provided replacement.

The method takes the following parameters:

NameDescription
patternThe pattern to look for in the string. Can be a string or a regular expression.
replacementA string used to replace the substring match by the supplied pattern.

# Only replacing/removing the spaces from the String with replaceAll()

In this particular scenario, there is no benefit to using the replaceAll() method over String.replace().

However, if you only need to remove spaces from the string (excluding tabs and newlines), you can pass a string instead of a regular expression to the replaceAll() method.

index.js
const str = ' A B C D '; const noWhitespace = str.replaceAll(' ', ''); console.log(noWhitespace); // ๐Ÿ‘‰๏ธ 'ABCD'
Instead of passing a regular expression to the replaceAll() method, we passed it a string containing a space.

The replaceAll() method removes all spaces by replacing them with empty strings.

Note that this approach only removes the spaces (not the tabs and newlines) from the string.

If you also want to remove the tabs and newline characters (\n), pass a regular expression to the method.

index.js
const str = ' A B C D '; const noWhitespace = str.replaceAll(/\s/g, ''); console.log(noWhitespace); // ๐Ÿ‘‰๏ธ 'ABCD'

If you need to replace the spaces in a string, specify a replacement string as the second argument to str.replaceAll().

index.js
const str = 'bobby hadz com'; const spacesReplaced = str.replaceAll(' ', '^'); console.log(spacesReplaced); // ๐Ÿ‘‰๏ธ 'bobby^hadz^com'

The code sample replaces all spaces in the string with a caret ^.

You can also create a reusable function if you have to replace the spaces in a string often.

index.js
function replaceAllSpaces(string, replacement) { return string.replaceAll(' ', replacement); } // ๐Ÿ‘‡๏ธ bobby-hadz console.log(replaceAllSpaces('bobby hadz', '-')); // ๐Ÿ‘‡๏ธ bobby!hadz!com console.log(replaceAllSpaces('bobby hadz com', '!'));

We defined a function that takes a string and a replacement as parameters and replaces all occurrences of a space in the string.

Alternatively, you can use the String.split() and Array.join() methods.

# Remove/Replace all spaces in a String using String.split()

This is a two-step process:

  1. Use the split() method to split the string into an array, on each occurrence of a space.
  2. Use the join() method to join the array into a string without a separator.
index.js
const str = 'bobby hadz com'; const withoutSpaces = str.split(' ').join(''); console.log(withoutSpaces); // ๐Ÿ‘‰๏ธ 'bobbyhadzcom'
The code for this article is available on GitHub

If you need to replace all spaces in a string, specify a replacement string in the call to Array.join().

index.js
const str = 'bobby hadz com'; const withoutSpaces = str.split(' ').join('^'); console.log(withoutSpaces); // ๐Ÿ‘‰๏ธ 'bobby^hadz^com'

We used the String.split() method to split the string on each space.

index.js
const str = 'bobby hadz com'; // ๐Ÿ‘‡๏ธ [ 'bobby', 'hadz', 'com' ] console.log(str.split(' '));

The String.split() method takes a separator and splits the string into an array on each occurrence of the provided delimiter.

The String.split() method takes the following 2 parameters:

NameDescription
separatorThe pattern describing where each split should occur.
limitAn integer used to specify a limit on the number of substrings to be included in the array.

The last step is to use the Array.join() method to all array elements with or without a separator.

If a value for the separator argument is omitted, the array elements are joined with a comma ,.

If the separator argument is set to an empty string, the array elements are joined without any characters in between them.

index.js
const str = 'bobby hadz com'; const withoutSpaces = str.split(' ').join(''); console.log(withoutSpaces); // ๐Ÿ‘‰๏ธ 'bobbyhadzcom'

If you need to replace the spaces in a string often, define a reusable function.

index.js
function replaceAllSpaces(string, replacement) { return string.split(' ').join(replacement); } // ๐Ÿ‘‡๏ธ bobby-hadz console.log(replaceAllSpaces('bobby hadz', '-')); // ๐Ÿ‘‡๏ธ bobby^hadz console.log(replaceAllSpaces('bobby hadz', '^'));
The code for this article is available on GitHub

The function takes a string and a replacement as parameters and replaces all occurrences of a space in the string.

When we pass an empty string to the split() method, we only split on the spaces (not the tabs, or newline characters).

If you also need to split on the tabs and newline characters, pass a regular expression to the String.split() method.

index.js
const str = 'bobby hadz com'; const withoutSpaces = str.split(/\s/).join(''); console.log(withoutSpaces); // ๐Ÿ‘‰๏ธ 'bobbyhadzcom'

The \s special character covers all whitespace characters (spaces, tabs and newlines).

# Conclusion

Which approach you pick is a matter of personal preference.

If you only have to remove/replace the spaces in a string (and not all whitespace characters), use the replaceAll method to avoid using a regular expression.

index.js
// โœ… remove all spaces from the string const str = 'bobby hadz com'; const result = str.replaceAll(' ', ''); console.log(result); // ๐Ÿ‘‰๏ธ bobbyhadzcom

The same approach can be used to replace all spaces in the string, you just have to specify a replacement string.

index.js
// โœ… replace all spaces in the string const str = 'bobby hadz com'; const result = str.replaceAll(' ', '^'); console.log(result); // ๐Ÿ‘‰๏ธ bobby^hadz^com

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev