Edit > Find & Replace

Search for: ^[ ]+|[ ]+$
Replace with:
Options: Regular expressions: ON
Click "Replace All".

In English, that pattern matches:

Beginning of text
A space, zero or more times
(Any character, zero or more times)
A space, zero or more times
End of text

The replacement represents the text that matched the part in parentheses, or everything except the spaces at the end.

Source