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);
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(' ');
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.
str.split(‘ ‘).filter(String) Then look at the array and only save the elements you need