0

I need to remove white-spaces while keeping the lines

Before:

I brought           a            Banana
I sold                a Banana
I           brought a Apple

After: NO WHITE SPACES or big space at the begining of the line

I brought a Banana
I sold a Banana
I brought a Apple

All of the tutorials removes the white space but it didn't keep me the lines so it became all the words in one line:

I need to do this because after I use the .replace method in JavaScript, I get a bunch of white spaces but need to keep the lines so I can reorder the words.

Elliot
  • 73
  • 8

3 Answers3

1

You can split the string with \n to map them:

var str = `I brought    a            Banana
I                   sold a Apple
I       sold a             Banana`;
str = str.split('\n').map(l => l.replace(/\s+/g,' ')).join('\n');
console.log(str);

OR: Simply str.replace(/[ \t]{1,}/g, ' ')

Where

\t matches a tab character (ASCII 9)

{1,} Quantifier — Matches between 1 and unlimited times, as many times as possible, giving back as needed

var str = `I    brought    a            Banana
I                   sold a Apple
I       sold a             Banana`;
str = str.replace(/[ \t]{1,}/g, ' ');
console.log(str);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Simply split the data by the space, filter them out and then add a single space.

var str = `I brought    a            Banana
I                   sold a Apple
I       sold a             Banana`;

str.split(' ').filter(String).join(' ');
Shaun Webb
  • 426
  • 5
  • 10
0

Simplest way

console.log(`I brought    a            Banana
I                   sold a Apple
I       sold a             Banana`.replace(/ +/g," "))
ahmet dundar
  • 92
  • 1
  • 5