Elliot
Elliot

Reputation: 93

How to remove all extra spaces while keeping the lines

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.

Upvotes: 1

Views: 791

Answers (3)

ahmet dundar
ahmet dundar

Reputation: 92

Simplest way

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

Upvotes: 0

Mamun
Mamun

Reputation: 68933

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

Upvotes: 2

Shaun Webb
Shaun Webb

Reputation: 426

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

Upvotes: 0

Related Questions