Javascript split at multiple delimters while keeping delimiters

丶灬走出姿态 提交于 2019-11-30 19:37:01

Why not something like this?

'div#container.blue'.split(/(?=[#.])/);

Because it's simply looking for a place where the next character is either # or the literal ., this does not capture anything, which makes it a zero length match. Because it's zero-length match, nothing is removed.

As you've probably found, the issue is that split removes the item you're splitting on. You can solve that with regex capturing groups (the parenthesis):

var result = 'div#container.blue'.split(/(#[^#|^.]*)|(\.[^#|^.]*)/);

Now we've got the issue that result contains a lot of falsy values you don't want. A quick filter fixes that:

var result = 'div#container.blue'.split(/(#[^#|^.]*)|(\.[^#|^.]*)/).filter(function(x) {
  return !!x;
});

Appendix A: What the heck is that regex

I'm assuming you're only concerned with # and . as characters. That still gives us this monster: /(#[^#|^.]*)|(\.[^#|^.]*)/

This means we'll capture either a # or ., and then all the characters up until the next # or . (remembering that a period is significant in regex, so we need to escape it, unless we're inside the brackets).

I've written an extensions of the Script type for you. It allows you to choose which delimiters to use, passing them in a string:

String.prototype.splitEx = function(delimiters) {
    var parts = [];
    var current = '';
    for (var i = 0; i < this.length; i++) {
        if (delimiters.indexOf(this[i]) < 0) current += this[i];
        else {
            parts.push(current);
            current = this[i];
        }
    }
    parts.push(current);
    return parts;
};

var text = 'div#container.blue';

console.log(text.splitEx('#.'));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!