Ana*_*ria 118 javascript
使用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;
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*Jon 349
这将删除最后一个逗号和后面的任何空格:
str = str.replace(/,\s*$/, "");
Run Code Online (Sandbox Code Playgroud)
它使用正则表达式:
该/
标记的开始和正则表达式的结束
本,
场比赛的逗号
这\s
意味着空格字符(空格,制表符等)和*
0或更多的平均值
将$
在最后表示该字符串的结尾
小智 10
你可以使用slice()方法从字符串中删除最后一个逗号,找到下面的例子:
var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
strVal = strVal.slice(0, -1);
}
Run Code Online (Sandbox Code Playgroud)
function removeLastComma(str) {
return str.replace(/,(\s+)?$/, '');
}
Run Code Online (Sandbox Code Playgroud)
如果它有用或更好的方法:
str = str.replace(/(\s*,?\s*)*$/, "");
Run Code Online (Sandbox Code Playgroud)
它将替换字符串的以下所有组合结尾:
1. ,<no space>
2. ,<spaces>
3. , , , , ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>
Run Code Online (Sandbox Code Playgroud)
大大赞成的答案不仅删除了最后一个逗号,还删除了后面的任何空格。但是删除后面的空格并不是原始问题的一部分。所以:
let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '
Run Code Online (Sandbox Code Playgroud)
https://jsfiddle.net/dc8moa3k/
归档时间: |
|
查看次数: |
141543 次 |
最近记录: |