[英]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.