JSFiddle - React, Tailwind, and code Playground
String splitVerbose
by skibulk
JavaScript
var str = '[gold2][combat3][health4]<p>Draw a card.<row>”Follow me!”';
//var search = "<p>";
var search = /\<[^<>]+?\>/g;
console.log(split(str, search));
console.log(splitVerbose(str, search));
function split(str, search) {
var out = [],
prev = 0,
match,
flags;
if (search instanceof RegExp) {
// search = new RegExp(search.source, search.global ? search.flags : search.flags + "g");
if (search.toString().match("\/[a-fh-z]*$")) {
alert("RegExp is missing global flag: " + search.toString());
exit();
}
}
do {
if (search instanceof RegExp) {
match = search.exec(str);
} else {
i = str.indexOf(search, prev);
(match = i < 0 ? false : [search]).index = i;
}
if (match) {
out.push(str.slice(prev, match.index));
prev = match.index + match[0].length;
} else {
out.push(str.slice(prev));
}
}
while (match);
return out;
}
// END function split
function splitVerbose(str, search) {
var out = [],
prev = 0,
match,
flags,
i;
if (search instanceof RegExp) {
// search = new RegExp(search.source, search.global ? search.flags : search.flags + "g");
if (search.toString().match("\/[a-fh-z]*$")) {
alert("RegExp is missing global flag: " + search.toString());
exit();
}
}
do {
if (search instanceof RegExp) {
match = search.exec(str);
} else {
i = str.indexOf(search, prev);
(match = i < 0 ? false : [search]).index = i;
}
if (match) {
out.push({
contents: str.slice(prev, match.index),
index: prev,
matched: false
});
out.push({
contents: match[0],
index: match.index,
matched:...