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

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

    Lets keep it simple: (add a "[ ]+" to your RegEx means "1 or more")

    This means "+" and "{1,}" are the same.

    var words = text.split(/[ .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/); // note ' and - are kept
    
    0 讨论(0)
  • 2020-11-21 23:41

    Perhaps you should do some sort of string replace to turn one separator into the other separator so you then only have one separator to deal with in your split.

    0 讨论(0)
  • 2020-11-21 23:41
    a = "a=b,c:d"
    
    array = ['=',',',':'];
    
    for(i=0; i< array.length; i++){ a= a.split(array[i]).join(); }
    

    this will return the string without a special charecter.

    0 讨论(0)
  • 2020-11-21 23:43

    Hi for example if you have split and replace in String 07:05:45PM

    var hour = time.replace("PM", "").split(":");
    

    Result

    [ '07', '05', '45' ]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 23:45

    An easy way to do this is to process each character of the string with each delimiter and build an array of the splits:

    splix = function ()
    {
      u = [].slice.call(arguments); v = u.slice(1); u = u[0]; w = [u]; x = 0;
    
      for (i = 0; i < u.length; ++i)
      {
        for (j = 0; j < v.length; ++j)
        {
          if (u.slice(i, i + v[j].length) == v[j])
          {
            y = w[x].split(v[j]); w[x] = y[0]; w[++x] = y[1];
          };
        };
      };
      
      return w;
    };
    

    console.logg = function ()
    {
      document.body.innerHTML += "<br>" + [].slice.call(arguments).join();
    }
    
    splix = function() {
      u = [].slice.call(arguments);
      v = u.slice(1);
      u = u[0];
      w = [u];
      x = 0;
      console.logg("Processing: <code>" + JSON.stringify(w) + "</code>");
    
      for (i = 0; i < u.length; ++i) {
        for (j = 0; j < v.length; ++j) {
          console.logg("Processing: <code>[\x22" + u.slice(i, i + v[j].length) + "\x22, \x22" + v[j] + "\x22]</code>");
          if (u.slice(i, i + v[j].length) == v[j]) {
            y = w[x].split(v[j]);
            w[x] = y[0];
            w[++x] = y[1];
            console.logg("Currently processed: " + JSON.stringify(w) + "\n");
          };
        };
      };
    
      console.logg("Return: <code>" + JSON.stringify(w) + "</code>");
    };
    
    setTimeout(function() {
      console.clear();
      splix("1.23--4", ".", "--");
    }, 250);
    @import url("http://fonts.googleapis.com/css?family=Roboto");
    
    body {font: 20px Roboto;}

    Usage: splix(string, delimiters...)

    Example: splix("1.23--4", ".", "--")

    Returns: ["1", "23", "4"]

    0 讨论(0)
提交回复
热议问题