我如何分裂一个字符串与多个分隔符在JavaScript?

我试图拆分逗号和空格,但AFAIK JavaScript的split()函数只支持一个分隔符。


当前回答

我很惊讶没有人建议它,但我的hack-ey(疯狂的快速)解决方案是附加几个“替换”调用之前由相同的字符分裂。

即删除a, b, c, d和e:

let str = 'afgbfgcfgdfgefg'
let array = str.replace('a','d').replace('b','d').replace('c','d').replace('e','d').split('d')

这可以方便地概括为一个拆分器数组,如下:

function splitByMany( manyArgs, string ) {
  do {
    let arg = manyArgs.pop()
    string = string.replace(arg, manyArgs[0])
  } while (manyArgs.length > 2)
  return string.split(manyArgs[0])
}

因此,在您的情况下,您可以调用

let array = splitByMany([" ", ","], 'My long string containing commas, and spaces, and more commas');

其他回答

让我们保持简单:(在你的RegEx中添加“[]+”表示“1或更多”)

这意味着“+”和“{1,}”是相同的。

var words = text.split(/[ .:;?!~,`"&|()<>{}\[\]\r\n/\\]+/); // note ' and - are kept

一个简单的方法是用每个分隔符处理字符串中的每个字符,并构建一个分隔符数组:

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;}

用法:splix(字符串,分隔符…) 示例:splix("1.23- 4", ".", "——") 返回:["1","23","4"]

My refactor of @Brian answer var string = 'and this is some kind of information and another text and simple and some egample or red or text'; var separators = ['and', 'or']; function splitMulti(str, separators){ var tempChar = 't3mp'; //prevent short text separator in split down //split by regex e.g. \b(or|and)\b var re = new RegExp('\\b(' + separators.join('|') + ')\\b' , "g"); str = str.replace(re, tempChar).split(tempChar); // trim & remove empty return str.map(el => el.trim()).filter(el => el.length > 0); } console.log(splitMulti(string, separators))

例如,如果你在String 07:05:45PM中使用了split and replace

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

结果

[ '07', '05', '45' ]

在Github上查看我的简单库

如果你真的不想访问或与repo交互,下面是工作代码:

/**
 * 
 * @param {type} input The string input to be split
 * @param {type} includeTokensInOutput If true, the tokens are retained in the splitted output.
 * @param {type} tokens The tokens to be employed in splitting the original string.
 * @returns {Scanner}
 */
function Scanner(input, includeTokensInOutput, tokens) {
    this.input = input;
    this.includeTokensInOutput = includeTokensInOutput;
    this.tokens = tokens;
}

Scanner.prototype.scan = function () {
    var inp = this.input;

    var parse = [];
    this.tokens.sort(function (a, b) {
        return b.length - a.length; //ASC, For Descending order use: b - a
    });
    for (var i = 0; i < inp.length; i++) {


        for (var j = 0; j < this.tokens.length; j++) {

            var token = this.tokens[j];
            var len = token.length;
            if (len > 0 && i + len <= inp.length) {
                var portion = inp.substring(i, i + len);
                if (portion === token) {
                    if (i !== 0) {//avoid empty spaces
                        parse[parse.length] = inp.substring(0, i);
                    }
                    if (this.includeTokensInOutput) {
                        parse[parse.length] = token;
                    }
                    inp = inp.substring(i + len);
                    i = -1;
                    break;
                }

            }

        }

    }
    if (inp.length > 0) {
          parse[parse.length] = inp;
    }

    return parse;


};

用法很简单:

    var tokens = new Scanner("ABC+DE-GHIJK+LMNOP", false , new Array('+','-')).scan();

console.log(tokens); 

给:

['ABC', 'DE', 'GHIJK', 'LMNOP']

如果您希望在输出中包含分隔令牌(+和-),将false设置为true,瞧!它仍然有效。

现在的用法是:

var tokens = new Scanner("ABC+DE-GHIJK+LMNOP", true , new Array('+','-')).scan();

and

console.log(tokens);

将:

['ABC', '+', 'DE', '-', 'GHIJK', '+', 'LMNOP']

享受吧!