Javascript Split Space Delimited String and Trim Extra Commas and Spaces

后端 未结 6 2364
时光说笑
时光说笑 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条回答
  •  梦毁少年i
    2021-02-19 15:52

    In addition to Felix Kling's answer

    If you have preceding and trailing white spaces, you should remove those first.

    It's possible to add an "extension method" to a JavaScript String by hooking into it's prototype. I've been using the following to trim preceding and trailing white-spaces, and thus far it's worked a treat:

    // trims the leading and proceeding white-space
    String.prototype.trim = function()
    {
        return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    };
    

提交回复
热议问题