Search code examples
javascriptregexmathmathjax

Change text to inline TeX with javascript and regex


I use the regex

/\$([^$]*)\$/g

to replace text inside two $'s with latex.

In javascript, I use

text.replace(/\$([^$]*)\$/g, function (str, match) {
    return changeToTeX(match);
}

It works almost as it should, but, for instance, this text

The price is between $400 and $500.

will be messed up because it thinks that it should convert 400 and to latex since this text is between dollar signs.

Maybe it is not possible to fix. I have just checked math.stackexchange.com which supports the same behaviour with text inside dollar signs being replaced by latex, but here the same problem is occuring with all text between dollar signs being interpreted as latex.


Solution

  • If you only have numbers inside $...$, use

    /\$(\d+)\$/g
    

    where \d+ matches 1 or more digit. The pattern inside can be enhanced to match any kind of numbers (see Matching Floating Point Numbers with a Regular Expression).

    To match anything but $ and whitespace, use

    /\$([^\s$]*)\$/g
    

    See this regex demo

    Possibly, to only require word chars after the first $ and before the last $, use

    /\B\$\b([^$]*)\b\$\B/g
    

    See another regex demo