How do I split a string with multiple separators in javascript?

前端 未结 22 1556
走了就别回头了
走了就别回头了 2020-11-21 23:14

How do I split a string with multiple separators in JavaScript? I\'m trying to split on both commas and spaces but, AFAIK, JS\'s split function only supports one separator.

22条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 23:58

    You can pass a regex into Javascript's split operator. For example:

    "1,2 3".split(/,| /) 
    ["1", "2", "3"]
    

    Or, if you want to allow multiple separators together to act as one only:

    "1, 2, , 3".split(/(?:,| )+/) 
    ["1", "2", "3"]
    

    (You have to use the non-capturing (?:) parens because otherwise it gets spliced back into the result. Or you can be smart like Aaron and use a character class.)

    (Examples tested in Safari + FF)

提交回复
热议问题