0

I am using regex to remove additional spaces. But I would like to keep single line-breaks.

'/\s+/'

How can I keep single line breaks?

Remove only extra unnecessary spaces and line-breaks.

I've tried '/\s{2,}/' but this still removes my line-breaks.

Maciek Semik
  • 1,872
  • 23
  • 43

1 Answers1

1

This will match extra spaces and new lines:

(?<= ) | +$|(?<=\n)\n

Explanation (space literals replaced with "[space]"):

(?<=[space])[space] | Match any space that has a preceding space
|                   | or
[space]+$           | Match one or more consecutive spaces at the end of a line
|                   | or
(?<=\n)\n           | Match any new line that has a preceding new line

The global and multi-line flags should be used with this expression. Simply replace the matches with nothing.

Try it here

Community
  • 1
  • 1
Adam
  • 3,829
  • 1
  • 21
  • 31