JSFiddle - React, Tailwind, and code Playground
by aneezbacker
JavaScript
/**
* @param text: string to be splitted
* @param regex: regex to be used as separator
*/
function split(text, regex) {
// resultArr will store the final result of splitting the string
var resultArr = null;
var matchesArr = text.split(new RegExp(regex));
/*
* Following code will check if String.split() charms us or not
*/
var charCount = 0;
for(var i=0; i<matchesArr.length; i++){
charCount += matchesArr[i].length;
}
if(charCount != text.length){
// Alas! String.split() sucks on this browser. Vodoo which will fix it follows
// separators are not included in the matchesArr.
var separatorsArr = text.match(new RegExp(regex, 'g'));
resultArr = new Array();
var resultArrIndex = 0;
var matchesIndex = 0;
var separatorsIndex = 0;
var partialResultArrText = "";
// following is a slightly modified version of array merge algorithm
while(matchesIndex<matchesArr.length && separatorsIndex<separatorsArr.length){
// we are checking what should be added to resultArr
if(text.search(partialResultArrText + matchesArr[matchesIndex]) == 0){
resultArr[resultArrIndex] = matchesArr[matchesIndex];
matchesIndex++;
} else {
resultArr[resultArrIndex] = separatorsArr[separatorsIndex];
separatorsIndex++;
}
partialResultArrText += resultArr[resultArrIndex];
resultArrIndex++;
}
if(matchesIndex < matchesArr.length ){
for (var i = matchesIndex; i < matchesArr.length; i++) {
resultArr[resultArrIndex] = matchesArr[i];
resultArrIndex++;
}
} else {
for (var i = separatorsIndex; i < separatorsArr.length; i++) {
resultArr[resultArrIndex] = separatorsArr[i];
...