remove unwanted commas in JavaScript

后端 未结 9 1627
青春惊慌失措
青春惊慌失措 2020-12-14 13:14

I want to remove all unnecessary commas from the start/end of the string.

eg; google, yahoo,, , should become google, yahoo.

If pos

9条回答
  •  醉话见心
    2020-12-14 13:43

    What you need to do is replace all groups of "space and comma" with a single comma and then remove commas from the start and end:

    trimCommas = function(str) {
        str = str.replace(/[,\s]*,[,\s]*/g, ",");
        str = str.replace(/^,/, "");
        str = str.replace(/,$/, "");
        return str;
    }
    

    The first one replaces every sequence of white space and commas with a single comma, provided there's at least one comma in there. This handles the edge case left in the comments for "Internet Explorer".

    The second and third get rid of the comma at the start and end of string where necessary.

    You can also add (to the end):

    str = str.replace(/[\s]+/, " ");
    

    to collapse multi-spaces down to one space and

    str = str.replace(/,/g, ", ");
    

    if you want them to be formatted nicely (space after each comma).

    A more generalized solution would be to pass parameters to indicate behaviour:

    • Passing true for collapse will collapse the spaces within a section (a section being defined as the characters between commas).
    • Passing true for addSpace will use ", " to separate sections rather than just "," on its own.

    That code follows. It may not be necessary for your particular case but it might be better for others in terms of code re-use.

    trimCommas = function(str,collapse,addspace) {
        str = str.replace(/[,\s]*,[,\s]*/g, ",").replace(/^,/, "").replace(/,$/, "");
        if (collapse) {
            str = str.replace(/[\s]+/, " ");
        }
        if (addspace) {
            str = str.replace(/,/g, ", ");
        }
        return str;
    }
    

提交回复
热议问题