Javascript Split Space Delimited String and Trim Extra Commas and Spaces

后端 未结 6 2390
时光说笑
时光说笑 2021-02-19 15:14

I need to split a keyword string and turn it into a comma delimited string. However, I need to get rid of extra spaces and any commas that the user has already input.



        
6条回答
  •  天命终不由人
    2021-02-19 16:09

    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

提交回复
热议问题