We encounter this problem all the time — needing to check if a string has whitespaces at the beginning and end. A simple solution is to use this regular expression, which allows you to validate a string with no whitespace at the beginning and end.
/^[^\s]+(\s+[^\s]+)*$/
Matches:
- abcdef
- 123456
- a1b1c1d1
Non-matches:
- <whitespace>abcdef
- abcdef<whitespace>
- <whitespace>abcdef<whitespace>
See Also:
- Regex To Match All Whitespace Except New Line
- Regular Expression To Match Whitespace
- Regex To Match Any Word In A String Excluding Spaces
- Regex To Match Anything After The First Space In A String