function plaintextLaTeX(str){
function parse(str){
let previous,
superDigit=[..."0123456789"].reduce((p,c,i)=>(p[i]=c,p),{"-":"-"}),
subDigit="0123456789";
do{
previous=str;
str=str.replace(/\\frac{([^{}]*)}{([^{}]*)}/g,(match,p1,p2)=>`(${parse(p1)})/(${parse(p2)})`); //Fractions
str=str.replace(/\\(\w+){([^{}]*)}/g,(match,p1,p2)=>`${p1}(${parse(p2)})`); //Math functions
str=str.replace(/_([0-9]+)/g,(match,p1)=>p1.split("").map(digit=>subDigit[digit]).join("")); //Subscript digits
str=str.replace(/\^(-?[0-9]+|{[^{}]*})/g,(match,p1)=>p1.startsWith('{')?p1.slice(1,-1).split("").map(digit=>superDigit[digit]||digit).join(""):superDigit[p1]||p1); //Superscript digits and braces
//Add asterisks for multiplications while avoiding LaTeX commands
//str=str.replace(/([a-z0-9])(?=(?<!\\[a-z]+)[a-z0-9])/gi,"$1*"); //Between two variables or digits
}while(previous!==str); //Continue until no changes are made
return str;
}
return parse(str);
}
console.log(plaintextLaTeX("H(z) = \\frac{b_0+b_1z^{-1}+b_2z^{-2}}{a_0+a_1z^{-1}+a_2z^{-2}}")); //This should output: "H(z) = (b0+b1*z-1+b2*z-2)/(a0+a1*z-1+a2*z-2)"
Is there a fully-fledged LaTeX to (inline) plaintext conversion for code documentation? (No big ASCII art, it utilizes Unicode math symbols instead. I also spent hours figuring out writing the RegExp, tokenization would be better at that point if you were to add more stuff)