795

How to remove spaces in a string? For instance:

Input:

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

Output:

'/var/www/site/Brandnewdocument.docx'
daaawx
  • 3,273
  • 2
  • 17
  • 16
Joseandro Luiz
  • 8,744
  • 4
  • 20
  • 20
  • 3
    my solution `" ahm ed ".split('').filter(e => e.trim().length).join('')` – U.A Feb 15 '20 at 09:52
  • 1
    @C.K Why is that better then `" ahm ed ".replace(/\s+/g, '');`? It seems like the slowest (in current Chrome) and most unreadable solution to me. https://jsfiddle.net/n74qsh50/ – Mark Baijens Mar 26 '21 at 14:05

15 Answers15

1732

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.

Jonathan
  • 2,700
  • 4
  • 23
  • 41
Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
  • @Gaurav I've looked up similar answers on SO, and I see `.replace(/\s+/g, '')` more often. Is there a difference between that and my answer? – Šime Vidas May 11 '11 at 11:17
  • in this case there is no difference. But + is used for finding with atleast one occurrence. – Gaurav May 11 '11 at 11:23
  • 3
    Silly me, I was under the impression that `.replace(' ','')` would work. Much appreciated! – Kelderic Oct 17 '14 at 21:31
  • 3
    original answer involving (which Sime linked to in his edit) `+` has only 60 votes if anyone wants to credit him/her too http://stackoverflow.com/a/5964427/4258817 – Mousey Sep 28 '15 at 15:01
  • 4
    Be careful not to accidentally quote your regex e.g. `.replace('/\s+/g', '')` because it'll try to find that literal string. This tripped me up before... – RTF Jun 04 '16 at 12:26
  • 1
    Keep in mind that `\s` (whitespace) is not the same as a normal space. This also include the characters linefeed, carriage return, tab, vertical tab, form feed and others. For more info have a look at the [JavaScript RegExp special characters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Using_special_characters). – 3limin4t0r Oct 01 '18 at 13:42
116

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

Community
  • 1
  • 1
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 1
    Interestingly, the split-join method is now the fastest for me on Firefox 73, followed by regexp1a at 53% slower. – hackel Jan 28 '20 at 05:03
113

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!

vsync
  • 118,978
  • 58
  • 307
  • 400
37

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, '')

Minstel
  • 586
  • 5
  • 10
  • @vsync He doesn't say it's "way faster", he says that the "*split join way* **is faster**". In other words, the "*split join method* **is faster**". He doesn't say how much faster, just that it is. – Self Evident Nov 17 '21 at 17:27
18

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

'/var/www/site/Brand new document.docx'.replaceAll(' ', '');
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Mrkouhadi
  • 446
  • 5
  • 14
16

easy way

someString.replace(/ /g, '');
// or
someString.replace(/\s/gm, '');
MD SHAYON
  • 7,001
  • 45
  • 38
10
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

Muhammad Tahir
  • 2,351
  • 29
  • 25
7

Without regexp, it works fine for only one occurrence.

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

This is faster as simple ! Could help some of you in some cases.

Meloman
  • 3,558
  • 3
  • 41
  • 51
  • 7
    because it removes just one space. replaceAll would remove all but the browser support is worse. – Tukkan Aug 31 '21 at 17:54
  • `replace` takes a `RegExp` or a string as its first argument which is known as `pattern`. If `pattern` is a string, only the first occurrence will be replaced. I would either go for a `RegExp` or for `replaceAll` – BonisTech Nov 30 '22 at 12:36
  • Thanks BonisTech and Tukkan, I just edited my answer to avoid misunderstanding. – Meloman Dec 01 '22 at 09:06
4
  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.

Raveendra007
  • 1,060
  • 1
  • 8
  • 13
4

You can use regex to remove spaces from string`

let str = '/var/www/site/Brand new document.docx';
let result = str.replace(/\s/g, '');
vitaretnama
  • 126
  • 3
2

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";
SoEzPz
  • 14,958
  • 8
  • 61
  • 64
  • I think explaining what is going is not really useful since you can easily wrap it into a function with the name removeWhiteSpace(string) { return string.replace(//g, '') } – Marnix Aug 09 '20 at 14:45
2

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.

shmuels
  • 1,039
  • 1
  • 9
  • 22
2

Easiest way to remove spaces from the string is use replace in this way

let str = '/var/www/site/Brand new document.docx';
let result = str.replace(/\s/g, '');
samran
  • 581
  • 6
  • 7
0

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

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


----------
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Tyler2P Jan 07 '21 at 15:14
-5
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

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Patrick Iradukunda
  • 499
  • 1
  • 5
  • 15