How to remove spaces from a string using JavaScript?

JavascriptText

Javascript Problem Overview


How to remove spaces in a string? For instance:

Input:

'/var/www/site/Brand new document.docx'

Output:

'/var/www/site/Brandnewdocument.docx'

Javascript Solutions


Solution 1 - Javascript

This?

str = str.replace(/\s/g, '');

Example

var str = '/var/www/site/Brand new document.docx';

document.write( str.replace(/\s/g, '') );


Update: Based on this question, this:

str = str.replace(/\s+/g, '');

is a better solution. It produces the same result, but it does it faster.

The Regex

\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).

A great explanation for + can be found here.

As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.

Solution 2 - Javascript

var a = b = " /var/www/site/Brand new   document.docx ";

console.log( a.split(' ').join('') );
console.log( b.replace( /\s/g, '') ); 

Two ways of doing this!

Solution 3 - Javascript

SHORTEST and FASTEST: str.replace(/ /g, '');


Benchmark:

Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):

SHORT strings

Short string similar to examples from OP question

enter image description here

The fastest solution on all browsers is / /g (regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join solution. Change to \s or add + or i to regexp slows down processing.

LONG strings

For string about ~3 milion character results are:

  • regexp1a: Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95
  • regexp2b: Safari 38.39, Firefox 19.45, Chrome 9.26
  • split-join: Firefox 26.41, Safari 23.10, Chrome 7.98,

You can run it on your machine: https://jsperf.com/remove-string-spaces/1

Solution 4 - Javascript

Following @rsplak answer: actually, using split/join way is faster than using regexp. See the performance test case

So

var result = text.split(' ').join('')

operates faster than

var result = text.replace(/\s+/g, '')

On small texts this is not relevant, but for cases when time is important, e.g. in text analisers, especially when interacting with users, that is important.


On the other hand, \s+ handles wider variety of space characters. Among with \n and \t, it also matches \u00a0 character, and that is what   is turned in, when getting text using textDomNode.nodeValue.

So I think that conclusion in here can be made as follows: if you only need to replace spaces ' ', use split/join. If there can be different symbols of symbol class - use replace(/\s+/g, '')

Solution 5 - Javascript

var input = '/var/www/site/Brand new document.docx';

//remove space
input = input.replace(/\s/g, '');

//make string lower
input = input.toLowerCase();

alert(input);

Click here for working example

Solution 6 - Javascript

easy way

someString.replace(/ /g, '');
// or
someString.replace(/\s/gm, '');

Solution 7 - Javascript

Without regexp, it works fine.

input = input.replace(' ', '');

Why not use simply this !? This is faster as simple !

Solution 8 - Javascript

You also use one of the latest string methods of JS: replaceAll

'/var/www/site/Brand new document.docx'.replaceAll(' ', '');

Solution 9 - Javascript

  var output = '/var/www/site/Brand new document.docx'.replace(/ /g, ""); 
    or
  var output = '/var/www/site/Brand new document.docx'.replace(/ /gi,"");

Note: Though you use 'g' or 'gi' for removing spaces both behaves the same.

If we use 'g' in the replace function, it will check for the exact match. but if we use 'gi', it ignores the case sensitivity.

for reference click here.

Solution 10 - Javascript

> Regex + Replace()

Although regex can be slower, in many use cases the developer is only manipulating a few strings at once so considering speed is irrelevant. Even though / / is faster than /\s/, having the '\s' explains what is going on to another developer perhaps more clearly.

let string = '/var/www/site/Brand new document.docx';
let path = string.replace(/\s/g, '');
// path => '/var/www/site/Brandnewdocument.docx'

> Split() + Join()

Using Split + Join allows for further chained manipulation of the string.

let string = '/var/www/site/Brand new document.docx';
let path => string.split('').map(char => /(\s|\.)/.test(char) ? '/' : char).join('');
// "/var/www/site/Brand/new/document/docx";

Solution 11 - Javascript

var str = '/var/www/site/Brand new document.docx';

document.write( str.replace(/\s\/g, '') );

Solution 12 - Javascript

Using replaceAll seems like the simplest cleanest way. (I can't vouch for fastest)

'/var/www/site/Brand new document.docx'.replaceAll(' ', '')

See docs.

>The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.

Solution 13 - Javascript

your_string = 'Hello world';
words_array = your_tring.split(' ');

string_without_space = '';

for(i=0; i<words_array.length; i++){
    new_text += words_array[i]; 
}

console.log("The new word:" new_text);

The output:

HelloWorld

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoseandro LuizView Question on Stackoverflow
Solution 1 - JavascriptŠime VidasView Answer on Stackoverflow
Solution 2 - Javascriptuser657496View Answer on Stackoverflow
Solution 3 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 4 - JavascriptMinstelView Answer on Stackoverflow
Solution 5 - JavascriptMuhammad TahirView Answer on Stackoverflow
Solution 6 - JavascriptMD SHAYONView Answer on Stackoverflow
Solution 7 - JavascriptMelomanView Answer on Stackoverflow
Solution 8 - JavascriptMrkouhadiView Answer on Stackoverflow
Solution 9 - JavascriptRaveendra007View Answer on Stackoverflow
Solution 10 - JavascriptSoEzPzView Answer on Stackoverflow
Solution 11 - Javascripthüseyin özlerView Answer on Stackoverflow
Solution 12 - JavascriptshmuelsView Answer on Stackoverflow
Solution 13 - JavascriptPatrick IradukundaView Answer on Stackoverflow