[Question] Importing the RegExp that MathJax uses to select Latex in Content?
fireflysemantics opened this issue · 3 comments
I have Latex expressions in Markdown and I need to select them.
They look something like this:
const md = `Some latex $$\\frac{\\sum_{i=1}^n$$ and some more latex $$MAD = \\frac{\\sum_{i=1}^n | x_i - \\bar{x} |} n$$`;
I was wondering if MathJax exposes the RegExp it uses to select the expressions so I could import it. Something like:
const regexp = require('MathJax').regexp
Then the selection could be performed like this:
s.match(regexp).map(v => v.substr(2, v.length - 4));
console.log(matches)
Thoughts?
MathJax doesn't use a RegExp for this. But it does have a module that will find the delimited math in an array of strings, and you can call on that.
const {FindTeX} = require('./js/input/tex/FindTeX.js');
const md = `Some latex $$\\frac{\\sum_{i=1}}^n$$ and some more latex $$MAD = \\frac{\\sum_{i=1}^n | x_i - \\bar{x} |} n$$`;
const find = new FindTeX({
//
// These are the default options, so not really needed, but are used as an example
//
inlineMath: [['\\(','\\)']] ,
displayMath: [['$$', '$$'], ['\\[', '\\]']],
processEscapes: true,
processEnvironments: true,
processRefs: true
});
console.log(find.findMath([md]));
will produce
[
{
open: '$$',
math: '\\frac{\\sum_{i=1}}^n',
close: '$$',
n: 0,
start: { n: 11 },
end: { n: 34 },
display: true
},
{
open: '$$',
math: 'MAD = \\frac{\\sum_{i=1}^n | x_i - \\bar{x} |} n',
close: '$$',
n: 0,
start: { n: 55 },
end: { n: 104 },
display: true
}
]
(I added a missing brace in your first expression.) The return value is an array of objects describing the math that has been identified. The properties give the open and close delimiters (open
and close
), the math itself (math
), the index into the array for the string containing the math (n
), the star and end locations in the string (start.n
, end.n
) and whether the math is display mode or not (display
).
So
matches = find.findMath([md]).map(item => item.math);
console.log(matches);
should get you what you describe above.
@dpvc THANK YOU! That's AWESOME! I have it working now. I'm so happy about this. I was trying to use RegEx for this and I think I was getting more gray hair by the hour. Thanks again!
Yes, regular expressions really don't work for this (the nesting of braces make it very difficult, in particular).