Una función de extensión divide la cadena con subcadena o RegEx y el delimitador se coloca según el segundo parámetro adelante o atrás.
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;
};
La prueba:
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"]);
});
si se conoce el delimitador de antemano, ¿por qué no hacer ... 'delim var = "
"; '? –
Gracias @SiGanteng, conozco el delimitador anterior pero no puedo hacerlo funcionar para mi ejemplo. Necesito mantener el delimitador como
seguido del carácter especial porque a veces puedo tener un
no seguido por el carácter especial y este no tiene que ser dividido. –
Buena pregunta, tengo un caso similar donde saber que el delimitador no ayuda. Me estoy dividiendo en "] y [". Entonces realmente mi delimitador es "&" pero dividirlo no es lo suficientemente preciso, necesito obtener los corchetes a cada lado para determinar una división adecuada. Sin embargo, necesito esos corchetes en mis cuerdas divididas. 1 en cada lado. – PandaWood