Javascript and regex: split string and keep the separator

后端 未结 7 2246
轮回少年
轮回少年 2020-11-22 05:25

I have a string:

var string = \"aaaaaa
† bbbb
‡ cccc\"

And I would like to split this string w

7条回答
  •  囚心锁ツ
    2020-11-22 06:12

    I made a modification to jichi's answer, and put it in a function which also supports multiple letters.

    String.prototype.splitAndKeep = function(separator, method='seperate'){
        var str = this;
        if(method == 'seperate'){
            str = str.split(new RegExp(`(${separator})`, 'g'));
        }else if(method == 'infront'){
            str = str.split(new RegExp(`(?=${separator})`, 'g'));
        }else if(method == 'behind'){
            str = str.split(new RegExp(`(.*?${separator})`, 'g'));
            str = str.filter(function(el){return el !== "";});
        }
        return str;
    };
    

    jichi's answers 3rd method would not work in this function, so I took the 4th method, and removed the empty spaces to get the same result.

    edit: second method which excepts an array to split char1 or char2

    String.prototype.splitAndKeep = function(separator, method='seperate'){
        var str = this;
        function splitAndKeep(str, separator, method='seperate'){
            if(method == 'seperate'){
                str = str.split(new RegExp(`(${separator})`, 'g'));
            }else if(method == 'infront'){
                str = str.split(new RegExp(`(?=${separator})`, 'g'));
            }else if(method == 'behind'){
                str = str.split(new RegExp(`(.*?${separator})`, 'g'));
                str = str.filter(function(el){return el !== "";});
            }
            return str;
        }
        if(Array.isArray(separator)){
            var parts = splitAndKeep(str, separator[0], method);
            for(var i = 1; i < separator.length; i++){
                var partsTemp = parts;
                parts = [];
                for(var p = 0; p < partsTemp.length; p++){
                    parts = parts.concat(splitAndKeep(partsTemp[p], separator[i], method));
                }
            }
            return parts;
        }else{
            return splitAndKeep(str, separator, method);
        }
    };
    

    usage:

    str = "first1-second2-third3-last";
    
    str.splitAndKeep(["1", "2", "3"]) == ["first", "1", "-second", "2", "-third", "3", "-last"];
    
    str.splitAndKeep("-") == ["first1", "-", "second2", "-", "third3", "-", "last"];
    

提交回复
热议问题