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



我有以下字符串称为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.  

预期输出:

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. 

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

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, ' ')
);

默认情况下,JavaScript 中的 string.replace 只会替换它找到的第一个匹配值,添加/g 将意味着所有匹配的值都被替换。

g 正则表达式修饰符(称为全局修饰符(基本上是向引擎表示在第一次匹配后不要停止解析字符串。

var string = "      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."
alert(string)
string = string.replace(/ +/g, ' ');
alert(string)

有用的修饰符列表:

  • g - 全局替换。替换提供的文本中匹配字符串的所有实例。
  • i - 不区分大小写的替换。替换匹配字符串的所有实例,忽略大小写差异。
  • m - 多行替换。应测试正则表达式是否跨多行匹配。

您可以将修饰符(如 g 和 i(组合在一起,以获得全局不区分大小写的搜索。

在angularjs中你可以使用trim()函数

const nameStr = '      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(nameStr.replace(/s+/g, ' ').trim());

let msg = '      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(msg.replace(/ss+/g, ' '));

最新更新