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

前端 未结 6 541
遥遥无期
遥遥无期 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:58

    input.split(/\s*[\s,]\s*/)

    \s* matches zero or more white space characters (not just spaces, but also tabs and newlines).

    ... [\s,] matches one white space character or one comma

    If you want to avoid blank elements from input like "foo,bar,,foobar", this will do the trick:

    input.split(/(\s*,?\s*)+/)

    The + matches one or more of the preceding character or group.

    Edit:

    Added ?after comma which matches zero or one comma.

    Edit 2:

    Turns out edit 1 was a mistake. Fixed it. Now there has to be at least one comma or one space for the expression to find a match.

提交回复
热议问题