Last active
April 29, 2022 11:01
-
-
Save gregelin/8787082 to your computer and use it in GitHub Desktop.
Very simple, fragile, multi-line text parsing in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Let's parse the lines in from our textarea | |
var textarea = $("#mytextarea").val(); | |
// Different browsers represent end of lines differently, so make all end of lines \n */ | |
lines = textarea.replace(/\r\n/g, "\n").split("\n"); | |
// Set up state variables to help track parsing across multiple lines | |
var line_parser_state = "listitem"; | |
var block_content = ""; | |
lines.forEach(function(entry) { | |
if (entry.trim()!="") { | |
// Line starts with ``` indicating start quote/code block if current state is "listitem" | |
if (entry.match(/```/) && "listitem" == line_parser_state ) { | |
// change states | |
line_parser_state = "codeblock" | |
// start code block | |
block_content = "<pre>"; | |
return; | |
} | |
// Line starts with ``` indicating end quote/code block if current state is "codeblock" | |
if (entry.match(/```/) && "codeblock" == line_parser_state) { | |
// append block_content and close code block | |
$("#timers").append(block_content + "</pre>"); | |
// reset line_parser_state | |
line_parser_state = "listitem"; | |
return; | |
} | |
// Line does not start with ``` indicating line of codeblock if current state is "codeblock" | |
if (!entry.match(/```/) && "codeblock" == line_parser_state ) { | |
// line that is part of code block | |
line_parser_state = "codeblock" | |
// append line to block_content | |
block_content = block_content + entry + "\n"; | |
return; | |
} | |
// Line starts with # - Create section heading and heading timer | |
if (entry.match(/#/)) { | |
line_parser_state = "sectionheading"; | |
// Remove `#`'s | |
entry = entry.replace(/#*/g,''); | |
$("#timers").append("<h4 style='border-bottom: 1px solid #ccc;'>"+entry+"</h4>\n"); | |
// Put heading as a timer in parantheses | |
entry = "("+entry+")"; | |
line_parser_state = "listitem"; | |
return; | |
} | |
// Line starts with keyword "Note:" or "comment:" - indicating a note or comment (case insentive) | |
if (entry.match(/note:|comment:/ig)) { | |
line_parser_state = "indentedline"; | |
$("#timers").append("<div style='margin-left:20px;'><i>"+entry.trim()+"</i></div>\n"); | |
entry = "("+entry+")"; | |
line_parser_state = "listitem"; | |
return; | |
} | |
// Append a line using a template | |
$("#timers").append($("#myformattemplate").val().replace(/{{entry}}/g, entry)); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment