Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <pre><code>trimCommas = function(str) { str = str.replace(/[,\s]*,[,\s]*/g, ","); str = str.replace(/^,/, ""); str = str.replace(/,$/, ""); return str; } </code></pre> <p>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".</p> <p>The second and third get rid of the comma at the start and end of string where necessary.</p> <p>You can also add (to the end):</p> <pre><code>str = str.replace(/[\s]+/, " "); </code></pre> <p>to collapse multi-spaces down to one space and</p> <pre><code>str = str.replace(/,/g, ", "); </code></pre> <p>if you want them to be formatted nicely (space after each comma).</p> <p>A more generalized solution would be to pass parameters to indicate behaviour:</p> <ul> <li>Passing <code>true</code> for <code>collapse</code> will collapse the spaces within a section (a section being defined as the characters between commas).</li> <li>Passing <code>true</code> for <code>addSpace</code> will use <code>", "</code> to separate sections rather than just <code>","</code> on its own.</li> </ul> <p>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.</p> <pre><code>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; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload