1

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.

5
  • 1
    str.replace(/[ \t]{2,}/g, ' ') Commented Feb 18, 2020 at 5:50
  • 1
    Does this answer your question? Regex to replace multiple spaces with a single space Commented Feb 18, 2020 at 5:50
  • Does this answer your question? Match whitespace but not newlines Commented Feb 18, 2020 at 6:01
  • you probably want str.replace(/[^\S\r\n]+/g,' '); Commented Feb 18, 2020 at 6:02
  • None of this code works for my situation, I don't know how to explain it Commented Feb 18, 2020 at 6:04

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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

Simplest way

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.