扩展函数使用子字符串或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"]);
});
如果你知道的分隔符事前,为什么不只是做...'VAR DELIM = “
”;'? – 2012-08-17 07:59:23
谢谢@SiGanteng,我知道预定义的分隔符,但我无法为我的例子工作。我需要保持分隔符为
,后面跟着特殊字符,因为有时候我可以有一个
,后面跟着特殊字符,这个字符不必被分割。 – 2012-08-17 08:02:45
好问题,我有一个类似的情况,知道分隔符没有帮助。我正在分裂“]和[”。所以实际上我的分隔符是“&”,但是分割并不够精确,我需要使用括号来确定正确的分割。不过,我需要将这些括号放回我的拆分字符串中。每一侧各有1个。 – PandaWood 2014-10-23 00:44:12