我有一个字符串:

var string = "aaaaaa<br />&dagger; bbbb<br />&Dagger; cccc"

我想用分隔符<br />拆分这个字符串,后面跟着一个特殊字符。

要做到这一点,我使用这个:

string.split(/<br \/>&#?[a-zA-Z0-9]+;/g);

我得到了我需要的东西,只是我丢失了分隔符。 示例如下:http://jsfiddle.net/JwrZ6/1/

如何保留分隔符?


当前回答

回答它这里也JavaScript分割正则表达式保持分隔符

在正则表达式中使用(?=pattern)前向模式 例子

var string = '500x500-11*90~1+1';
string = string.replace(/(?=[$-/:-?{-~!"^_`\[\]])/gi, ",");
string = string.split(",");

这将得到以下结果。

[ '500x500', '-11', '*90', '~1', '+1' ]

还可以直接拆分吗

string = string.split(/(?=[$-/:-?{-~!"^_`\[\]])/gi);

给出相同的结果

[ '500x500', '-11', '*90', '~1', '+1' ]

其他回答

回答它这里也JavaScript分割正则表达式保持分隔符

在正则表达式中使用(?=pattern)前向模式 例子

var string = '500x500-11*90~1+1';
string = string.replace(/(?=[$-/:-?{-~!"^_`\[\]])/gi, ",");
string = string.split(",");

这将得到以下结果。

[ '500x500', '-11', '*90', '~1', '+1' ]

还可以直接拆分吗

string = string.split(/(?=[$-/:-?{-~!"^_`\[\]])/gi);

给出相同的结果

[ '500x500', '-11', '*90', '~1', '+1' ]

扩展函数将字符串与子字符串或RegEx分开,分隔符根据第二个参数放在前面或后面。

    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;
    };

测试:

    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"]);
    });

如果你对拆分模式进行分组,它的匹配将被保留在输出中,这是通过设计的:

如果separator是带有捕获括号的正则表达式,则 每次分隔符匹配时,结果(包括任何未定义的 捕获括号的结果)拼接到输出中 数组中。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split#description

除非您的搜索模式使用前瞻性或全局标志,否则您不需要这些标志。

const str = '如果一只土拨鼠会扔木头,它会扔多少木头?` Const result = str.split(/(\s+)/); console.log(结果); //我们可以验证结果 const isSame = result.join(") === str; console.log({isSame});

您可以使用多个组。你可以尽情发挥你的创造力,小组之外的内容将被删除:

const str = '如果一只土拨鼠会扔木头,它会扔多少木头?` Const result = str.split(/(\s+)(\w{1,2})\w+/); console.log(结果,result.join ("));

我知道这有点晚了,但你也可以使用搜索

Var string = "aaaaaa<br />&dagger;bbbb < br / >匕首;预备”; Var数组= string.split(/(?< = < br \ / >) /); console.log(数组);

我遇到了类似但略有不同的问题。无论如何,这里有三种不同场景的示例,用于说明在何处保存分隔符。

"1、2、3".split("、") == ["1", "2", "3"]
"1、2、3".split(/(、)/g) == ["1", "、", "2", "、", "3"]
"1、2、3".split(/(?=、)/g) == ["1", "、2", "、3"]
"1、2、3".split(/(?!、)/g) == ["1、", "2、", "3"]
"1、2、3".split(/(.*?、)/g) == ["", "1、", "", "2、", "3"]

警告:第四个只适用于拆分单个字符。ConnorsFan提供了一个替代方案:

// Split a path, but keep the slashes that follow directories
var str = 'Animation/rawr/javascript.js';
var tokens = str.match(/[^\/]+\/?|\//g);