[英]remove unwanted commas in JavaScript
我想從字符串的開頭/結尾刪除所有不必要的逗號。
例如; google, yahoo,, ,
應該成為google, yahoo
。
如果可能的話,google,, , yahoo,, ,
應該成為google,yahoo
。
我已經嘗試了以下代碼作為起點,但它似乎沒有按預期工作。
trimCommas = function(s) {
s = s.replace(/,*$/, "");
s = s.replace(/^\,*/, "");
return s;
}
在您的示例中,如果逗號在開頭或結尾處有空格,您還需要修剪逗號,使用如下所示的內容:
str.replace(/^[,\s]+|[,\s]+$/g, '').replace(/,[,\s]*,/g, ',');
注意使用'g'修飾符進行全局替換。
你需要這個:
s = s.replace(/[,\s]{2,}/,""); //Removes double or more commas / spaces
s = s.replace(/^,*/,""); //Removes all commas from the beginning
s = s.replace(/,*$/,""); //Removes all commas from the end
編輯:做出所有的改變 - 現在應該工作。
我的看法:
var cleanStr = str.replace(/^[\s,]+/,"")
.replace(/[\s,]+$/,"")
.replace(/\s*,+\s*(,+\s*)*/g,",")
這個將適用於opera, internet explorer, whatever
實際測試了最后一個,它的工作原理!
你需要做的是用一個逗號替換所有“空格和逗號”組,然后從開頭和結尾刪除逗號:
trimCommas = function(str) {
str = str.replace(/[,\s]*,[,\s]*/g, ",");
str = str.replace(/^,/, "");
str = str.replace(/,$/, "");
return str;
}
第一個用一個逗號替換每個空格和逗號序列,只要其中至少有一個逗號。 這將處理“Internet Explorer”注釋中留下的邊緣大小寫。
第二個和第三個在必要時刪除字符串開頭和結尾的逗號。
你也可以添加(到最后):
str = str.replace(/[\s]+/, " ");
將多個空間折疊到一個空間和
str = str.replace(/,/g, ", ");
如果你希望它們被很好地格式化(每個逗號后面的空格)。
更通用的解決方案是傳遞參數以指示行為:
collapse
傳遞true
將折疊一個部分中的空格(一個部分被定義為逗號之間的字符)。 addSpace
傳遞true
將使用", "
來分隔部分而不僅僅是","
。 該代碼如下。 對於您的特定情況可能沒有必要,但在代碼重用方面可能對其他人更好。
trimCommas = function(str,collapse,addspace) {
str = str.replace(/[,\s]*,[,\s]*/g, ",").replace(/^,/, "").replace(/,$/, "");
if (collapse) {
str = str.replace(/[\s]+/, " ");
}
if (addspace) {
str = str.replace(/,/g, ", ");
}
return str;
}
首先在Google上ping“Javascript Trim”: http : //www.somacon.com/p355.php 。 你似乎用逗號實現了這個,我不明白為什么它會成為一個問題(雖然你在第二個而不是在第一個中逃脫)。
不太復雜,但簡單:
',google,, , yahoo,, ,'.replace(/\s/g, '').replace(/,+/g, ',');
您應該只能使用一個替換呼叫:
/^( *, *)+|(, *(?=,|$))+/g
測試:
'google, yahoo,, ,'.replace(/^( *, *)+|(, *(?=,|$))+/g, '');
"google, yahoo"
',google,, , yahoo,, ,'.replace(/^( *, *)+|(, *(?=,|$))+/g, '');
"google, yahoo"
分解:
/
^( *, *)+ # Match start of string followed by zero or more spaces
# followed by , followed by zero or more spaces.
# Repeat one or more times
| # regex or
(, *(?=,|$))+ # Match , followed by zero or more spaces which have a comma
# after it or EOL. Repeat one or more times
/g # `g` modifier will run on until there is no more matches
(?=...)
是一個向前看將不會移動匹配的位置但只驗證一個字符在匹配之后。 在我們的案例中,我們尋找,或EOL
match()比replace()更好的工具
str = " aa, bb,, cc , dd,,,";
newStr = str.match(/[^\s,]+/g).join(",")
alert("[" + newStr + "]")
當你想要替換",," ",,,", ",,,,"
和",,,,,"
,代碼將被","
刪除。
var abc = new String("46590,26.91667,75.81667,,,45346,27.18333,78.01667,,,45630,12.97194,77.59369,,,47413,19.07283,72.88261,,,45981,13.08784,80.27847,,");
var pqr= abc.replace(/,,/g,',').replace(/,,/g, ',');
alert(pqr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.