从字符串中删除最后一个逗号 [英] Remove Last Comma from a string
本文介绍了从字符串中删除最后一个逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用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
这篇关于从字符串中删除最后一个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文