如何使用 javascript 从字符串末尾删除多个逗号?

How to remove multiple comma from end of string using 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

您可以按照以下方式进行;

var str = "9781473507340.epub,9781473518902.epub,,,,,,",
 newStr = str.replace(/,*(?=$)/,"");
console.log(newStr);

可能有点矫枉过正,但你可以试试这样的方法。

可以遵循这些步骤。

  1. 根据逗号拆分为使用 split() 的数组。
  2. 过滤掉空白项。
  3. 使用join()将新数组放回字符串。

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);