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

时间:2018-09-18 09:33:09

标签: 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.  

预期输出:

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. 

4 个答案:

答案 0 :(得分: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, ' ')
);

答案 1 :(得分:2)

在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());

答案 2 :(得分:2)

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(/\s\s+/g, ' '));

答案 3 :(得分:2)

默认情况下,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等修饰词组合在一起,以进行不区分大小写的全局搜索。