Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用javascript替换字符串中的html实体(LaTeX)命令_Javascript_Regex_Replace_Command_Latex - Fatal编程技术网

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

用javascript替换字符串中的html实体(LaTeX)命令,javascript,regex,replace,command,latex,Javascript,Regex,Replace,Command,Latex,我有一个LaTeX命令/html实体字典: var translations = [ {tex: '\\latex', html: 'LaTeX'}, {tex: '\\cup', html: '∪'}, {tex: '\\cap', html: '∩'}, {tex: '\\ldots', html: '…'}, {tex: '\\leftarrow', html: '←'}, {tex: '\\leftrightarrow', html: '↔

我有一个LaTeX命令/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;
}
例如,这在一定程度上是可行的

\leftarrow \leftrightarrow becomes ← ↔
\leftarrow\leftrightarrow becomes ←\leftrightarrow instead ←↔
但是比如说,

\leftarrow \leftrightarrow becomes ← ↔
\leftarrow\leftrightarrow becomes ←\leftrightarrow instead ←↔
我猜这是因为第二个
\cup
的反斜杠成为第一个的替换部分,因此不再匹配

基本结构也是有效的吗


非常感谢您的帮助。

问题在于正则表达式中的最后一个子模式是一个否定字符类,它实际使用输入,在下一次迭代中没有机会匹配下一个实体

只需将其放置在具有非否定字符类的负前瞻中:

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


有关(以及一般的lookarounds)的详细信息,请参见。

我已经检查了最后一个正则表达式,似乎您只是使用了tex后面的字母。请将其放入一个lookahead:
\\leftarrow(?=[^a-zA-Z])
。或者,只需使用单词边界
\\leftarrow\b
(这意味着在非单词之前匹配
w
(而不是
[a-zA-Z0-9\]
字符)。也就是说,
var re=RegExp('\\'+Tools.SVG.translations[k].tex+'\\b',g');
。谢谢。不幸的是,对于字符串末尾的命令它不起作用。(LaTeX实际上接受
\leftarrow7
作为命令
\leftarrow
,后跟(非命令)编号
7
。因此单词边界不起作用。但先行功能起作用。)注意:我还想在命令末尾删除一个可选的空格,这样就可以将
a\leftarrow B
的最小空格设置为
a←B
(\\s|(?![a-zA-Z]))
您甚至可以使用非捕获组:
(?:\\s|(?![a-zA-Z]))
(保持regex捕获缓冲区干净)。谢谢。虽然我不确定“保持regex捕获缓冲区干净”是什么意思……对不起,我通过复制和粘贴(
Tools.SVG.translations=translations
)将变量名弄乱了。我将字符串结尾字符
$
添加到了前瞻中,以同时匹配字符串结尾:
(?=[^a-zA-Z]|$)
。是否正确?将负前瞻与正字符类一起使用,您不需要以我添加正则表达式演示的方式指定字符串结尾替代项。