[英]How to trim spaces between word, and after comma using 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, ' ') );
在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(/\\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)组合在一起,以获得全局不区分大小写的搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.