将 (LaTeX) 命令替换为 html 字符串中的实体 javascript

Replace (LaTeX) commands by html entities in string with javascript

我有 LaTeX commands/html 个实体的字典:

var translations = [
    {tex: '\latex', html: 'LaTeX'},
    {tex: '\cup', html: '∪'},
    {tex: '\cap', html: '∩'},
    {tex: '\ldots', html: '…'},
    {tex: '\leftarrow', html: '←'},
    {tex: '\leftrightarrow', html: '↔'}
    ...
];

现在我想用 html 实体替换每个 LaTeX 命令。我想最好的基本结构是这样的:

function translateFromTexToHTML(string) {
    for (i = 0; i < translations.length; i += 1) {
        re = new RegExp('...\' + translations[i].tex + '...');
        string = string.replace(re, '...' + translations[i].html);
    }
    return string;
}

不幸的是,我不知道我需要哪个正则表达式。我试过这个:

var re = new RegExp('\' + translations[k].tex + '([^a-zA-Z])', 'g');
string .replace(re, translations[k].html + '');

这部分有效,例如,

\leftarrow \leftrightarrow becomes ← ↔

但是,例如,

\leftarrow\leftrightarrow becomes ←\leftrightarrow instead ←↔

我猜这是因为第二个 \cup 的反斜杠替换了第一个的反斜杠,因此不再匹配。

还有基本结构高效吗?

非常感谢帮助。

问题是正则表达式中的最后一个子模式是取反字符 class,实际上 消耗 输入,在下一次迭代期间没有机会匹配下一个实体.

只需将它放在带有非否定字符的否定前瞻中 class:

\leftarrow(?![a-zA-Z])

var re = RegExp('\' + translations[k].tex + '(?![a-zA-Z])', 'g');

regex demo

上查看更多信息(一般来说,lookarounds)。