Skip to content Skip to sidebar Skip to footer

Single Regex To Remove Empty Lines And Double Spaces From Multiline Input

I would like to combine two regex functions to clean up some textarea input. I wonder if it is even possible, or if I should keep it two separate ones (which work fine but aren't l

Solution 1:

I'd suggest the following expression with a substitution template "$1$2" (demo):

/^\s*|\s*$|\s*(\r?\n)\s*|(\s)\s+/g

Explanation:

  • ^\s* - matches whitespace from the text beginning
  • \s*$ - matches whitespace from the text ending
  • \s*(\r?\n)\s* - matches whitespace between two words located in different lines, captures one CRLF to group $1
  • (\s)\s+ - captures the first whitespace char in a sequence of 2+ whitespace chars to group $2

Post a Comment for "Single Regex To Remove Empty Lines And Double Spaces From Multiline Input"