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?
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?
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 , ' ');
Out of curiosity I tested a variant with split
/ join
, but with regex is faster .
Option for non-RegEx users:
var str = "00000.00000 111111111.111111111111 33333333";
while (str.indexOf(' ') != -1) str = str.replace(' ', ' ');
console.log(str);
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