How to delete duplicate spaces in a string?

16

I have the following string :

var str = "00000.00000  111111111.111111111111  33333333"

I need to remove the extra spaces for it to be like this (only with 1 space):

var str = "00000.00000 111111111.111111111111 33333333"

How do I proceed?

    
asked by anonymous 25.05.2014 / 02:14

3 answers

17

You can use a regular expression for this:

var str = "00000.00000  111111111.111111111111  33333333"
str = str.replace(/\s{2,}/g, ' ');

Splitting the regex and replace into parts:

  • \s - any whitespace
  • {2,} - in quantity of two or more
  • g - catch all occurrences, not just the first
  • then replace replaces these groups of spaces so that it is passed in the second parameter. In this case a simple space , ' ');

Out of curiosity I tested a variant with split / join , but with regex is faster .

    
25.05.2014 / 02:16
3

Option for non-RegEx users:

var str = "00000.00000  111111111.111111111111  33333333";
while (str.indexOf('  ') != -1) str = str.replace('  ', ' ');
console.log(str);
    
07.11.2016 / 13:12
0

It has a very interesting way too that works for almost any language. Worth the curiosity.

var str = '00000.00000  111111111.111111111111  33333333';

str = str.split(' ').join('<>');
str = str.split('><').join('');
str = str.split('<>').join(' ');

console.log(str);

Note: Works for 2 or more spaces

    
08.11.2016 / 13:16