text.replace(/^\s+|\s+$/g, '') removes whitespace from both ends of a string and leaves the inside alone. The pattern has two alternatives: ^\s+ is the whitespace at the start, and \s+$ the whitespace at the end. The g flag matters: without it, replace() stops after the first match, and only the start gets trimmed.
In the tester below, Hello, world! with a tab at the end becomes Hello, world!: the three spaces in the middle stay.
Just use trim()
In JavaScript, text.trim() does exactly this, and it’s faster and clearer. It removes the same characters as \s: spaces, tabs, line breaks, the no-break space and the other Unicode spaces. trimStart() and trimEnd() do one side each. The regex earns its place where there’s no trim(), such as in a search-and-replace box, in a config file that takes a pattern, or in a chain of replacements.
Collapsing the inside too
To also squeeze every run of whitespace inside the string down to one space:
text.trim().replace(/\s+/g, ' '); // "Hello, world!"
Trimming every line
With the m flag, ^ and $ match at every line, so it looks as if /^\s+|\s+$/gm trims each line. It does more than that: \s matches line breaks too, so it swallows blank lines and can join lines together.
' a \n\n b '.replace(/^\s+|\s+$/gm, ''); // "ab"
' a \n\n b '.replace(/^[^\S\r\n]+|[^\S\r\n]+$/gm, ''); // "a\n\nb"
[^\S\r\n] reads as “not a non-whitespace character, and not a line break”, which is whitespace other than line breaks. Use it whenever a pattern must stay on one line.
Other languages
The same pattern works almost everywhere, with one difference to watch: what \s covers. In JavaScript it includes the no-break space, U+00A0, which often arrives in text pasted from web pages. Java’s \s is ASCII-only unless you set the UNICODE_CHARACTER_CLASS flag, and Java’s trim() removes only characters up to U+0020, so both leave a no-break space in place.