Javascript and regex: split string and keep the separator

后端 未结 7 2252
轮回少年
轮回少年 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:11

    An extension function splits string with substring or RegEx and the delimiter is putted according to second parameter ahead or behind.

        String.prototype.splitKeep = function (splitter, ahead) {
            var self = this;
            var result = [];
            if (splitter != '') {
                var matches = [];
                // Getting mached value and its index
                var replaceName = splitter instanceof RegExp ? "replace" : "replaceAll";
                var r = self[replaceName](splitter, function (m, i, e) {
                    matches.push({ value: m, index: i });
                    return getSubst(m);
                });
                // Finds split substrings
                var lastIndex = 0;
                for (var i = 0; i < matches.length; i++) {
                    var m = matches[i];
                    var nextIndex = ahead == true ? m.index : m.index + m.value.length;
                    if (nextIndex != lastIndex) {
                        var part = self.substring(lastIndex, nextIndex);
                        result.push(part);
                        lastIndex = nextIndex;
                    }
                };
                if (lastIndex < self.length) {
                    var part = self.substring(lastIndex, self.length);
                    result.push(part);
                };
                // Substitution of matched string
                function getSubst(value) {
                    var substChar = value[0] == '0' ? '1' : '0';
                    var subst = '';
                    for (var i = 0; i < value.length; i++) {
                        subst += substChar;
                    }
                    return subst;
                };
            }
            else {
                result.add(self);
            };
            return result;
        };
    

    The test:

        test('splitKeep', function () {
            // String
            deepEqual("1231451".splitKeep('1'), ["1", "231", "451"]);
            deepEqual("123145".splitKeep('1', true), ["123", "145"]);
            deepEqual("1231451".splitKeep('1', true), ["123", "145", "1"]);
            deepEqual("hello man how are you!".splitKeep(' '), ["hello ", "man ", "how ", "are ", "you!"]);
            deepEqual("hello man how are you!".splitKeep(' ', true), ["hello", " man", " how", " are", " you!"]);
            // Regex
            deepEqual("mhellommhellommmhello".splitKeep(/m+/g), ["m", "hellomm", "hellommm", "hello"]);
            deepEqual("mhellommhellommmhello".splitKeep(/m+/g, true), ["mhello", "mmhello", "mmmhello"]);
        });
    

提交回复
热议问题