Written at 5am because I thought it was an interesting problem.
// Input:
// _string_ -> string
// *string* -> string
// [link|text] -> text, text is optional
// Handles missing links and link text
// Handles unterminated format strings
function getParts(str, endChar) {
const uIndex = str.indexOf(endChar);
let toProcess = "";
if (uIndex >= 0) {
toProcess = str.substring(0, uIndex);
theRest = str.substring(uIndex + 1);
} else {
toProcess = str;
theRest = "";
}
return { toProcess, theRest };
}
function formatStr(input) {
let result = "";
let remaining = input;
const fmtChars = /[_*[]/;
while (remaining) {
let firstFmt = remaining.search(fmtChars);
if (firstFmt < 0) {
result += remaining;
remaining = ""; // Done
} else {
result += remaining.substr(0, firstFmt);
switch (remaining.charAt(firstFmt)) {
case '_':
{
const { toProcess, theRest } = getParts(remaining.substr(firstFmt + 1), "_");
remaining = theRest;
result += "<em>" +
formatStr(toProcess) +
"</em>";
}
break;
case '*':
{
const { toProcess, theRest } = getParts(remaining.substr(firstFmt + 1), "*");
remaining = theRest;
result += "<strong>" +
formatStr(toProcess) +
"</strong>";
}
break;
case '[':
{
const { toProcess, theRest } = getParts(remaining.substr(firstFmt + 1), "*");
remaining = theRest;
const parts = toProcess.split("|", 2);
const link = parts.length > 0 && parts[0] ? parts[0] : "http://youforgot.com";
const linkText = parts.length > 1 ? parts[1] : link;
result += "<a href="\""" +="" link="" "\"="">" +
linkText +
"</a>";
}
break;
}
}
}
return result;
}
function test() {
let input1 = "test _italics_ and *bold*";
console.log(input1 + " -> " + formatStr(input1));
let input2 = "test [link|a link] and more";
console.log(input2 + " -> " + formatStr(input2));
let input3 = "This is a bold italic link *_[http://example.com|to example.com]_* and some _*bold italic* italics_";
console.log(input3 + " -> " + formatStr(input3));
let input4 = "unterminated test *_[http://example.com|to example.com]";
console.log(input4 + " -> " + formatStr(input4));
let input5 = "empty link [] and partial [http//link.com] ";
console.log(input5 + " -> " + formatStr(input5));
}