Javascript Split Space Delimited String and Trim Extra Commas and Spaces
In ES6:
var temp = str.split(",").map((item)=>item.trim());
You will need a regular expression in both cases. You could split and join the string:
str = str.split(/[\s,]+/).join();
This splits on and consumes any consecutive white spaces and commas. Similarly, you could just match and replace these characters:
str = str.replace(/[\s,]+/g, ',');
For the trailing comma, just append one
str = .... + ',';
If you have preceding and trailing white spaces, you should remove those first.
Reference: .split
, .replace
, Regular Expressions