如何使用javascript从字符串结尾删除多个逗号?
这是我的输出如何使用javascript从字符串结尾删除多个逗号?
9781473507340.epub,9781473518902.epub,,,,,,
我需要这个输出
9781473507340.epub,9781473518902.epub
仅使用动态地javascript.It可能获取文件名获取动态
要删除所有尾随逗号,你可以使用这个正则表达式:
var str = "9781473507340.epub,9781473518902.epub,,,,,,";
var res = str.trim().replace(/,{1,}$/, '');
console.log(res); // 9781473507340.epub,9781473518902.epub
好奇心,有没有原因使用'{1,}'而不是'+'? –
不,不是真的@NadiaCerezo,都应该做同样的工作。 – baao
是的,当然,他们是一样的,我只是好奇你为什么会喜欢前者而不是后者。 ^^ –
你可能会这样做,
var str = "9781473507340.epub,9781473518902.epub,,,,,,",
newStr = str.replace(/,*(?=$)/,"");
console.log(newStr);
可能是矫枉过正,但你可以尝试这样的事情。
可以遵循这些步骤。
var input = '9781473507340.epub,9781473518902.epub,,,,,,';
var output = input
.split(',') //split to array
.filter(function(val, b){
return val.length
}) //filter out the blank items
.join(','); //put the new array to a string.
console.log(output);
为什么你有这个逗号?你有控制输出吗? –
你是如何得到这么多逗号的?你在追加字符串吗? – Arti
请添加更多详细信息来解释您的问题 – Arti