Regex To Remove Unnecessary Spaces In A String

A regular expression to match unnecessary whitespaces in a string (excluding spaces between words). Can be useful in removing all unexpected white spaces at the beginning or end of strings.

/^\s+|\s+$|\s+(?=\s)/

Matches:

  • RegexPattern<SPACE>
  • <SPACE>RegexPattern

Non-matches:

  • Regex<SPACE>Pattern

See Also: