删除"不必要的"空格

Blu*_*ire 0 javascript regex replace

我想从字符串中删除所有"不必要的"空格.特别:

"a b c d" => "a b c d" // spaces between two words are left in
" a b c d " => "a b c d" // spaces not between two words are removed
"a  b c   d" => "a b c d" // as are duplicate spaces
Run Code Online (Sandbox Code Playgroud)

有什么正则表达式我可以String.replace()为我做这个吗?

Bar*_*mar 5

使用trim()的字符串和正则表达式替换的两端删除空间在中间来替代多个空格.

str = str.trim().replace(/\s{2,}/g, ' ');
Run Code Online (Sandbox Code Playgroud)