[英]Remove spaces and quotes outside words and leave one space between words
我有一個帶有引號和空格的字符串,如' TEST 123 '
或" TEST 123 "
。 如何刪除單詞外的空格和引號,並在單詞之間留一個空格。 預期結果: TEST 123
newString = string.replace(/\\s+/g,''); // "thiscontainsspaces"
newString = string.replace(/\\s+/g,' ').trim();
你可以使用這個正則表達式,
^[ '"]+|[ '"]+$|( ){2,}
並將其替換為$1
,其中$1
捕獲單個空格,但例如有兩個或多個空格。
這里, ^[ '"]+
匹配字符串開頭的任何空格或單引號或雙引號一個或多個,類似地[ '"]+$
也匹配字符串末尾的任何空格或單引號或雙引號一個或多個並被替換with 空字符串 where as when ( ){2,}
匹配,在字符串中間仍然匹配,被替換為 group1 中捕獲的單個空格。
示例JS演示,
var arr = ["' TEST 123 '",'" TEST 123 "']; for (s of arr) { console.log(s + " --> " + s.replace(/^[ '"]+|[ '"]+$|( ){2,}/g,'$1')); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.