I have a dictionary for LaTeX commands/html entities:
var translations = [
{tex: '\\latex', html: 'LaTeX'},
{tex: '\\cup', html: '∪'},
{tex: '\\cap', html: '∩'},
{tex: '\\ldots', html: '…'},
{tex: '\\leftarrow', html: '←'},
{tex: '\\leftrightarrow', html: '↔'}
...
];
Now I want to replace each LaTeX command by its html entity. I guess the best basic structure is like this:
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;
}
Unfortunately, I cannot figure out which regular expression I need. I tried this:
var re = new RegExp('\\' + translations[k].tex + '([^a-zA-Z])', 'g');
string .replace(re, translations[k].html + '$1');
This partly works, for example,
\leftarrow \leftrightarrow becomes ← ↔
But, for example,
\leftarrow\leftrightarrow becomes ←\leftrightarrow instead ←↔
I guess it is because the backslash of the second \cup
becomes part of the replacement of the first and hence is not matched anymore.
Also is the basic structure efficient?
Help much appreciated.