I am allowing users to type in BBCodes that convert to MathJax; however, there's a problem, as you can see below.
function chatFormat(text){
text = text.replace('\\', '');
text = text.replace(/\[f\](.+?)\/(.+?)\[\/f\]/igm, '\\( \\frac{\\text{$1}}{\\text{$2}} \\)');
text = text.replace(/\[eq\](.+?)\[\/eq\]/igm, '\\( $1 \\)');
text = text.replace(/(.+?)\^(.+?)/igm, '\\( $1^{\\text{$2}} \\)');
text = text.replace(/\[sqrt\](.+?)\[\/sqrt\]/igm, '\\( \\sqrt{\\text{$1}} \\)');
return text;
}
Works almost fine. It converts the BBCodes into the appropriate commands flawlessly; however, there is a problem if you begin to nest commands. e.g.:
If a user types in:
[eq]15^2 = [sqrt]225[/sqrt][/eq]
It will be converted to:
\( 15^{2} = \( \sqrt{225} \) \)
^ ^
| |
| |
| |
HOW TO AVOID
How can I avoid the extra \(
and \)
when they nest BBCodes, like the square root command inside the [eq]
bbcode?
Thanks!
This is something that will likely be very hard with regular expressions, because you can't use them to match arbitrarily nested patterns (see e.g. Can regular expressions be used to match nested patterns? ). If you do need this kind of sophisticated nested parsing, you're better of writing a real parser... Or better yet, since BBCode is so common, using one that already exists. Here's one that looks fairly extensible and may suit your needs: https://github.com/patorjk/Extendible-BBCode-Parser