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

前端 未结 22 1930
走了就别回头了
走了就别回头了 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:43

    For fun, I solved this with reduce and filter. In real life I would probably use Aarons answere here. Nevertheless I think my version isn't totally unreadable or inefficient:

    [' ','_','-','.',',',':','@'].reduce(
    (segs, sep) => segs.reduce(
    (out, seg) => out.concat(seg.split(sep)), []), 
    ['E-mail Address: user@domain.com, Phone Number: +1-800-555-0011']
    ).filter(x => x)
    

    Or as a function:

    function msplit(str, seps) {
      return seps.reduce((segs, sep) => segs.reduce(
        (out, seg) => out.concat(seg.split(sep)), []
      ), [str]).filter(x => x);
    }
    

    This will output:

    ['E','mail','Address','user','domain','com','0','Phone','Number','+1','800','555','0011']
    

    Without the filter at the end you would get empty strings in the array where two different separators are next to each other.

提交回复
热议问题