This will remove the last comma and any whitespace after it:
str = str.replace(/,\s*$/, "");
It uses a regular expression:
-
The
/mark the beginning and end of the regular expression -
The
,matches the comma -
The
\smeans whitespace characters (space, tab, etc) and the*means 0 or more -
The
$at the end signifies the end of the string