从字符串中删除最后一个逗号
问题描述:
使用JavaScript,如何删除最后一个逗号,但前提是逗号是最后一个字符,或者逗号后面只有空格?这是我的代码. 我有一个正在工作的小提琴.但是它有一个错误.
Using JavaScript, how can I remove the last comma, but only if the comma is the last character or if there is only white space after the comma? This is my code. I got a working fiddle. But it has a bug.
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;
}
答
这将删除最后一个逗号及其后的所有空格:
This will remove the last comma and any whitespace after it:
str = str.replace(/,\s*$/, "");
它使用正则表达式:
-
/
标记正则表达式的开始和结束
The
/
mark the beginning and end of the regular expression
,
与逗号匹配
\s
表示空白字符(空格,制表符等),而*
表示0个或更多
The \s
means whitespace characters (space, tab, etc) and the *
means 0 or more
末尾的$
表示字符串的末尾
The $
at the end signifies the end of the string