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

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


当前回答

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))

其他回答

对于那些希望在拆分函数中进行更多自定义的人,我编写了一个递归算法,它使用要拆分的字符列表拆分给定的字符串。在我看到上面的帖子之前,我写了这篇文章。我希望它能帮助一些沮丧的程序员。

splitString = function(string, splitters) {
    var list = [string];
    for(var i=0, len=splitters.length; i<len; i++) {
        traverseList(list, splitters[i], 0);
    }
    return flatten(list);
}

traverseList = function(list, splitter, index) {
    if(list[index]) {
        if((list.constructor !== String) && (list[index].constructor === String))
            (list[index] != list[index].split(splitter)) ? list[index] = list[index].split(splitter) : null;
        (list[index].constructor === Array) ? traverseList(list[index], splitter, 0) : null;
        (list.constructor === Array) ? traverseList(list, splitter, index+1) : null;    
    }
}

flatten = function(arr) {
    return arr.reduce(function(acc, val) {
        return acc.concat(val.constructor === Array ? flatten(val) : val);
    },[]);
}

var stringToSplit = "people and_other/things";
var splitList = [" ", "_", "/"];
splitString(stringToSplit, splitList);

上面的例子返回:["people", "and", "other", "things"]

注:flatten函数取自Rosetta Code

不是最好的方法,但适用于使用多个和不同的分隔符/分隔符进行分割

html

<button onclick="myFunction()">Split with Multiple and Different seperators/delimiters</button>
<p id="demo"></p>

javascript

<script>
function myFunction() {

 var str = "How : are | you doing : today?";
 var res = str.split(' | ');

 var str2 = '';
 var i;
 for (i = 0; i < res.length; i++) { 
    str2 += res[i];
    
    if (i != res.length-1) {
      str2 += ",";
    }
 }
 var res2 = str2.split(' : ');

 //you can add countless options (with or without space)

 document.getElementById("demo").innerHTML = res2;
}
</script>

棘手的方法:

var s = "dasdnk asd, (naks) :d skldma";
var a = s.replace('(',' ').replace(')',' ').replace(',',' ').split(' ');
console.log(a);//["dasdnk", "asd", "naks", ":d", "skldma"]

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

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

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

从@stephen-sweriduk解决方案开始(这对我来说更有趣!),我对它进行了轻微的修改,使其更加通用和可重用:

/**
 * Adapted from: http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
*/
var StringUtils = {

  /**
   * Flatten a list of strings
   * http://rosettacode.org/wiki/Flatten_a_list
   */
  flatten : function(arr) {
    var self=this;
    return arr.reduce(function(acc, val) {
        return acc.concat(val.constructor === Array ? self.flatten(val) : val);
    },[]);
  },

  /**
   * Recursively Traverse a list and apply a function to each item
   * @param list array
   * @param expression Expression to use in func
   * @param func function of (item,expression) to apply expression to item
   *
   */
  traverseListFunc : function(list, expression, index, func) {
    var self=this;
    if(list[index]) {
        if((list.constructor !== String) && (list[index].constructor === String))
            (list[index] != func(list[index], expression)) ? list[index] = func(list[index], expression) : null;
        (list[index].constructor === Array) ? self.traverseListFunc(list[index], expression, 0, func) : null;
        (list.constructor === Array) ? self.traverseListFunc(list, expression, index+1, func) : null;
    }
  },

  /**
   * Recursively map function to string
   * @param string
   * @param expression Expression to apply to func
   * @param function of (item, expressions[i])
   */
  mapFuncToString : function(string, expressions, func) {
    var self=this;
    var list = [string];
    for(var i=0, len=expressions.length; i<len; i++) {
        self.traverseListFunc(list, expressions[i], 0, func);
    }
    return self.flatten(list);
  },

  /**
   * Split a string
   * @param splitters Array of characters to apply the split
   */
  splitString : function(string, splitters) {
    return this.mapFuncToString(string, splitters, function(item, expression) {
      return item.split(expression);
    })
  },

}

然后

var stringToSplit = "people and_other/things";
var splitList = [" ", "_", "/"];
var splittedString=StringUtils.splitString(stringToSplit, splitList);
console.log(splitList, stringToSplit, splittedString);

归还原物的:

[ ' ', '_', '/' ] 'people and_other/things' [ 'people', 'and', 'other', 'things' ]