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

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

    Starting from @stephen-sweriduk solution (that was the more interesting to me!), I have slightly modified it to make more generic and reusable:

    /**
     * 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

    and then

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

    that gives back as the original:

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

提交回复
热议问题