Solution 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);

Solution 2 :

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(' ');

Solution 3 :

Simplest way

console.log(`I brought    a            Banana
I                   sold a Apple
I       sold a             Banana`.replace(/ +/g," "))

Problem :

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.

Comments

Comment posted by Jayce444

str.replace(/[ t]{2,}/g, ‘ ‘)

Comment posted by Regex to replace multiple spaces with a single space

Does this answer your question?

Comment posted by Match whitespace but not newlines

Does this answer your question?

Comment posted by Eaten by a Grue

you probably want

Comment posted by Elliot

None of this code works for my situation, I don’t know how to explain it

Comment posted by Shaun Webb

str.split(‘ ‘).filter(String) Then look at the array and only save the elements you need

By