![](/img/trans.png)
[英]JavaScript regular expression for the validation of comma separated string
[英]Filter Comma and Whitespace in String using Regular Expression in JavaScript
我想使用正則表達式過濾字符串,以便:
樣本輸入:
" , 這是 A ,,,, Test , , 在 js 123 中查找正則表達式, "
預期輸出:
“這是一個測試,在 js 123 中找到正則表達式”
到目前為止我嘗試過的:
我想出了一個到目前為止有效的解決方案。
var str = " , This, is A ,,, Test , , to find regex,,in js 123 , "; str = str.replace(/ +/g, " "); //replace multiple space with single space str = str.replace(/\\s*,\\s*/g, ","); //replace space before and after comma with single comma str = str.replace(/,+/g, ","); //remove multiple comma with single comma str = str.replace(/^,|,$/g, ""); //remove starting and ending comma console.log(str);
首先,刪除逗號旁邊的所有空格:
replace(/ *, */g, ’,’)
其次,將所有連續逗號替換為單個逗號並將所有連續空格替換為單個空格:
replace(/,+/g, ‘,’)
replace(/ +/g, ‘ ‘)
最后,刪除開頭和結尾的逗號:
replace(/^,/, ‘’)
replace(/,$/, ‘’)
var str = " , This, is A ,,, Test , , to find regex,,in js 123 , "; str = str.replace(/^[\\s,]+|[\\s,]+$|\\s*(\\s|,)[\\s,]*/g, "$1"); console.log(str);
到目前為止,我已經提出了一個可行的解決方案。
var str =“,這是A ,,,Test,,以在js 123中找到正則表達式,”;
str = str.replace(/ +/g, " "); //replace multiple space with single space
str = str.replace(/\s*,\s*/g, ","); //replace space before and after comma with single comma
str = str.replace(/,+/g, ","); //remove multiple comma with single comma
str = str.replace(/^,|,$/g, ""); //remove starting and ending comma
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.