Skip to content

Instantly share code, notes, and snippets.

@cyrusfirheir
Last active August 20, 2020 05:00
Show Gist options
  • Save cyrusfirheir/23d5bd8e3de8bcc53790e2e8c8a47c49 to your computer and use it in GitHub Desktop.
Save cyrusfirheir/23d5bd8e3de8bcc53790e2e8c8a47c49 to your computer and use it in GitHub Desktop.
Splits text into parts based on a regexp of headers and returns an array of objects with the header and the content. (description is WIP)
//split text by headers (headerRegex, noOfCaptureGroupsInHeaderToReturn)
if(!String.prototype.headsplit) {
Object.defineProperty(String.prototype, 'headsplit', {
configurable: true,
writable: true,
value: function headsplit(regexp, caps = 1) {
const text = this.trim().split(/\r?\n/);
let retArr = [],
_header = "",
_content = "",
_caps = "";
for (let c = 0; c < caps; c++) {
_caps += ("\$" + (c + 1) + ".____.");
}
_caps = _caps.slice(0, -6);
for (let t = 0; t < text.length; t++) {
if (regexp.test(text[t])) {
retArr.push({
header: _header.trim(),
content: _content.trim()
});
_header = text[t].replace(regexp, _caps);
_content = "";
} else {
_content += (text[t] + "\n");
}
if (t === (text.length - 1)) {
retArr.push({
header: _header.trim(),
content: _content.trim()
});
}
}
retArr.shift();
return retArr;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment