Javascript Split Space Delimited String and Trim Extra Commas and Spaces

后端 未结 6 2381
时光说笑
时光说笑 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:15

    I would keep it simple, and just match anything not allowed instead to join on:

    str.split(/[^a-zA-Z-]+/g).filter(v=>v);
    

    This matches all the gaps, no matter what non-allowed characters are in between. To get rid of the empty entry at the beginning and end, a simple filter for non-null values will do. See detailed explanation on regex101.

    var str = ", ,, ford,    tempo, with,,, sunroof,, ,";
    
    var result = str.split(/[^a-zA-Z-]+/g).filter(v=>v).join(',');
    
    console.info(result);

提交回复
热议问题