How to delete duplicate spaces in a string?

Asked

Viewed 11,309 times

18

I have the following string:

var str = "00000.00000  111111111.111111111111  33333333"

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

var str = "00000.00000 111111111.111111111111 33333333"

How should I proceed?

3 answers

25


You can use a regular expression for this:

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

Dividing the Regex and replace in parts:

  • \s - any white space
  • {2,} - in quantities of two or more
  • g - catch all occurrences, not only the first
  • after replace makes the subsitution of these groups of spaces by what is passed in the second parameter. In this case a single space , ' ');

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

  • 1

    Perfect friend, thank you!!

6

Option for those who do not want Regex:

var str = "00000.00000  111111111.111111111111  33333333";
while (str.indexOf('  ') != -1) str = str.replace('  ', ' ');
console.log(str);

I put in the Github for future reference.

2

There is a very interesting way also that works practically for any language. Worth the curiosity.

let str = '00000.00000  111111111.111111111111  33333333';

str = str.split(' ').join('<>');
console.log('Passo 1:', str);
str = str.split('><').join('');
console.log('Passo 2:', str);
str = str.split('<>').join(' ');
console.log('Resultado:', str);

or

let str = '00000.00000  111111111.111111111111  33333333';

str = str.replace(/[ ]/g, '<>');
console.log('Passo 1:', str);
str = str.replace(/></g, '');
console.log('Passo 2:', str);
str = str.replace(/<>/g, ' ');
console.log('Resultado:', str);

Obs: Works for 2 or more spaces

Browser other questions tagged

You are not signed in. Login or sign up in order to post.