0

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!

X33
  • 1,310
  • 16
  • 37

1 Answers1

1

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

Community
  • 1
  • 1
caseygrun
  • 2,019
  • 1
  • 15
  • 21
  • Sorry, which link do you feel needs to be better explained in the answer? The first points to a highly upvoted stackoverflow topic on this general matter (why regular expressions are inappropriate for parsing nested expressions), while the second link points to a library that could solve this specific problem. – caseygrun Oct 01 '14 at 05:02