Remove Last Comma from a string

前端 未结 10 1204
轻奢々
轻奢々 2020-11-30 19:52

Using JavaScript, how can I remove the last comma, but only if the comma is the last character or if there is only white space after the comma? This is my code. I got a wor

10条回答
  •  野性不改
    2020-11-30 20:04

    The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:

    let str = 'abc,def,ghi, ';
    let str2 = str.replace(/,(?=\s*$)/, '');
    alert("'" + str2 + "'");
    'abc,def,ghi '
    

    https://jsfiddle.net/dc8moa3k/

提交回复
热议问题