How to Remove Spaces From String

In today’s tutorial, we will show you simple solutions for removing spaces from a string and explain each step.

replace()

If you want to remove all the space in the string then, you can use the replace() method:

Javascript replace method remove all the space
let str = '/var/www/site/New document.docx'; console.log(str.replace(/\s+/g, '')); // /var/www/site/Newdocument.docx

Here \s is the regex for whitespace, and g is short for the global flag, which means match all \s (whitespaces). Each contiguous string of space characters is replaced with the empty string because of “+”.

You can also use another version:

Javascript replace method remove all the space
let str = '/var/www/site/New document.docx'; console.log(str.replace(/\s/g, '')); // /var/www/site/Newdocument.docx

You can add content between the single quotes whatever you want to replace whitespace with any string. For example if you type '#', you will grap the difference:

Javascript replace method remove all the space
let str = 'New document'; console.log(str.replace(/\s/g, '#')); // New#document console.log(str.replace(/\s+/g, '#')); // New#document
However, the /\s+/g is much faster than /\s/g.

split() and join()

The split() and join() methods can also be used to delete the space from the given string:

Javascript split and join methods delete the space
let str = " /var/www/site/New document.docx "; console.log(str.split(' ').join(''));

You can use any of these two fast methods, however, take into account the following facts:

  • If you need to replace spaces ' ', use the split/join method.
  • If there are wide range of symbols use replace(/\s+/g, '').

The replace() Method

The replace() method executes a search for a match in a string, and replaces the matched substring with a replacement substring. The pattern can be either a string or a regex. The replacement can be either a string or a function to be called for each match. If the pattern is a string, only the first occurrence will be replaced.

The split() and join() Methods

The split() method cuts a string into an ordered set of substrings, puts them into an array, and returns it. The division is achieved by searching for a pattern, which is provided as the first parameter in the method's call. To reverse the split, call join(). which will create an array items string along with glue between them.