使用JavaScript,如何删除最后一个逗号,但前提是逗号是最后一个字符,或者逗号后面只有空格?这是我的代码。我有一个工作小提琴。但是它有一个错误。
var str = 'This, is a test.';
alert( removeLastComma(str) ); // should remain unchanged
var str = 'This, is a test,';
alert( removeLastComma(str) ); // should remove the last comma
var str = 'This is a test, ';
alert( removeLastComma(str) ); // should remove the last comma
function removeLastComma(strng){
var n=strng.lastIndexOf(",");
var a=strng.substring(0,n)
return a;
}
是否还应该删除最后的空格?
—
Felix Kling
如果只有空格,是的
—
AnaMaria
逗号前的空格如何?是否也应将其删除?在这种情况下:str = str.replace(/,\ s * $ /,“”); 将成为str = str.replace(/ \ s *,\ s * $ /,“”);
—
阿米塔布(Amitabh)