How can I split a JavaScript string by white space or comma?

前端 未结 6 527
遥遥无期
遥遥无期 2020-12-12 15:10

If I try

\"my, tags are, in here\".split(\" ,\")

I get the following

[ \'my, tags are, in here\' ]

Wherea

6条回答
  •  暖寄归人
    2020-12-12 15:47

    The suggestion to use .split(/[ ,]+/) is good, but with natural sentences sooner or later you'll end up getting empty elements in the array. e.g. ['foo', '', 'bar'].

    Which is fine if that's okay for your use case. But if you want to get rid of the empty elements you can do:

    var str = 'whatever your text is...';
    str.split(/[ ,]+/).filter(Boolean);
    

提交回复
热议问题