Quote (squirrel @ May 21 2019 07:46pm)
Not sure if you still need this.. but it was decently fun.
Code
var input = "Category A:\n\
line 1\n\
line 2\n\
line 3\n\
line 4\n\
\n\
Category B:\n\
line 5\n\
line 6\n\
line 7\n\
\n\
Category A:\n\
line 8\n\
line 9\n\
line 10\n\
\n\
Category B:\n\
Line 11";
var split = input.split("\n");
var builder = {};
var lastCategorySeen = "";
for (var i = 0; i < split.length; i++) {
var so = split[i].trim(); //trim will remove a character return (\r) if it's there
if (so.length > 0) {
if (so.endsWith(":")) {//ends with : so is a category..
var sotc = so.substring(0, so.length - 1); //trim last char which is colon
lastCategorySeen = sotc;
if (typeof builder[sotc] === "undefined") {
builder[sotc] = []; //define the category in builder object with empty array
}
}
else {
//it's not a category so simply add it to the last seen category
if ((lastCategorySeen || "") !== "") { //prevents an error if a category wasn't defined ie.. the first line of the input isn't a category
builder[sotc].push(so);
}
}
}
}
//rebuild the string if that's important to you...
var stringBuilder = [];
for (var cat in builder) {
stringBuilder.push(cat + ":");
for (var i = 0; i < builder[cat].length; i++) {
stringBuilder.push(builder[cat][i]);
}
stringBuilder.push("");
}
var ret = stringBuilder.join("\n"); // set to \r\n if char return is needed (windows)
console.log(ret);
Thanks for the great code. Payment sent.