JSFiddle - React, Tailwind, and code Playground
by Josh Pullen
JavaScript
import katex from "https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.mjs";
function isValidLatexString(str) {
try {
katex.renderToString(str, { strict: true, throwOnError: true });
return true;
} catch (err) {
return false;
}
}
let str = String.raw`x = \left(\frac{a}{2b}\right)^2`;
let strings = str.split(/\\\w+/g);
console.log(strings);
let allValidSubstrings = [];
strings.map(str => {
for (let a = 0; a < str.length; a++) {
for (let b = a + 1; b < str.length; b++) {
const substr = str.slice(a, b);
if (isValidLatexString(substr)) {
allValidSubstrings.push(substr);
}
}
}
})
console.log(JSON.stringify(allValidSubstrings, null, 2));