在多个分隔符处分割Javascript,同时保留分隔符 [英] Javascript split at multiple delimters while keeping delimiters
本文介绍了在多个分隔符处分割Javascript,同时保留分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有比我现有的方法(例如通过正则表达式)更好的方法
Is there a better way than what I have (through regex, for instance) to turn
"div#container.blue"
进入此
["div", "#container", ".blue"];
这就是我所拥有的...
Here's what I've have...
var arr = [];
function process(h1, h2) {
var first = h1.split("#");
arr.push(first[0]);
var secondarr = first[1].split(".");
secondarr[0] = "#" + secondarr[0];
arr.push(secondarr[0]);
for (i = 1; i< secondarr.length; i++) {
arr.push(secondarr[i] = "." + secondarr[i]);
}
return arr;
}
推荐答案
为什么不这样?
'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.
这篇关于在多个分隔符处分割Javascript,同时保留分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文