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

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


当前回答

下面是在ES6中实现相同的新方法:

SplitByString(source, splitBy) { var splitter = splitBy.split("); splitter.push([源]);//推送初始值 返回分配器。reduceRight(函数(累加器,curValue) { Var k = []; 蓄电池。v => k =[…k…v.split (curValue)]); 返回k; }); } Var source = "abc,def#hijk*lmn,opq#rst*uvw,xyz"; var splitBy = ",*#"; splitBy console.log (SplitByString(源));

在这个函数中请注意:

不涉及正则表达式 以源代码中显示的相同顺序返回拆分后的值

以上代码的结果为:

其他回答

棘手的方法:

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

我使用regexp:

str =  'Write a program that extracts from a given text all palindromes, e.g. "ABBA", "lamal", "exe".';

var strNew = str.match(/\w+/g);

// Output: ["Write", "a", "program", "that", "extracts", "from", "a", "given", "text", "all", "palindromes", "e", "g", "ABBA", "lamal", "exe"]

从@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' ]

下面是使用Regex可能会有帮助的一些情况:

\W匹配其他任何字符[a-zA-Z0-9_]。例子:

("Hello World,I-am code").split(/\W+/); // would return [ 'Hello', 'World', 'I', 'am', 'code' ]

一个或多个空格 \d来匹配数字 如果你想用一些字符来分割,你可以使用str.split(/[,-]+/)

我用缩减和过滤解决了这个问题。它可能不是最易读的解决方案,也不是最快的,在现实生活中,我可能会在这里使用aaron的答案,但写起来很有趣。

[' ','_','-','.',',',':','@'].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)

或作为一个函数:

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

这将输出:

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

如果没有最后的过滤器,你将在数组中得到空字符串,其中两个不同的分隔符彼此相邻。