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

前端 未结 22 1908
走了就别回头了
走了就别回头了 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: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 += "
    " + [].slice.call(arguments).join(); } splix = function() { u = [].slice.call(arguments); v = u.slice(1); u = u[0]; w = [u]; x = 0; console.logg("Processing: " + JSON.stringify(w) + ""); for (i = 0; i < u.length; ++i) { for (j = 0; j < v.length; ++j) { console.logg("Processing: [\x22" + u.slice(i, i + v[j].length) + "\x22, \x22" + v[j] + "\x22]"); 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: " + JSON.stringify(w) + ""); }; 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"]

提交回复
热议问题