如何修剪单词之间的空格,以及使用javascript后的逗号

Pho*_*nix 4 javascript angularjs

我有一个名为name的字符串,我希望修剪一个句子中的单词之间的空格,并在逗号之后修剪空格.我可以在句子的开头和结尾使用trim()修剪额外的空格.
[我正在使用javascript来实现我的代码]

name = '      Barack Hussein       Obama II is an     American politician who served       as the 44th President        of the United States from January 20,    2009,    to January 20, 2017.  
Run Code Online (Sandbox Code Playgroud)

预期产出:

name = ' Barack Hussein  Obama II is an American politician who served  as the 44th President of the United States from January 20, 2009, to January 20, 2017. 
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 6

假设剩余的双空格只是一个拼写错误,您可以使用正则表达式匹配一个或多个空格,并用一个空格替换每个空格:

const name1 = '      Barack Hussein       Obama II is an     American politician who served       as the 44th President        of the United States from January 20,    2009,    to January 20, 2017.';
console.log(
  name1.replace(/ +/g, ' ')
);
Run Code Online (Sandbox Code Playgroud)