Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用javascript修剪单词之间和逗号后的空格_Javascript_Angularjs - Fatal编程技术网

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

如何使用javascript修剪单词之间和逗号后的空格,javascript,angularjs,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

我有一个名为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=“巴拉克·侯赛因·奥巴马二世是一位美国政治家,从2009年1月20日至2017年1月20日担任美国第44任总统。”;
console.log(
名称1.替换(/+/g'')

);在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=“巴拉克·侯赛因·奥巴马二世是一位美国政治家,从2009年1月20日至2017年1月20日担任美国第44任总统。”;

console.log(msg.replace(/\s\s+/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)组合在一起,以获得全局不区分大小写的搜索