如何替换数组?

时间:2013-07-09 08:51:52

标签: javascript regex

以下代码(来自stackedit - 降价编辑器)将取代

\begin{thm}
blabla...
\end{thm}

<div class="latex_thm">
blabla...
</div>

代码是:

userCustom.onEditorConfigure = function(editor) {
    var converter = editor.getConverter();
    converter.hooks.chain("preConversion", function(text) {
        return text.replace(/\\begin{thm}([\s\S]*?)\\end{thm}/g, function(wholeMatch, m1) {
            return '<thm>' + m1 + '</thm>';
        });
    });
    converter.hooks.chain("preBlockGamut", function(text, blockGamutHookCallback) {
        return text.replace(/<thm>([\s\S]*?)<\/thm>/g, function(wholeMatch, m1) {
            return '<div class="latex_thm">' + blockGamutHookCallback(m1) + '</div>';
        });
    });
};

但是,如果我不仅要将thm替换为latex_thm,还要将lem替换为latex_lem,如何执行此操作?我想也许用array来解决它?但同样对我不起作用:

userCustom.onEditorConfigure = function(editor) {
    var converter = editor.getConverter();
    converter.hooks.chain("preConversion", function(text) {
        var array = {
            "thm": "thm",
            "lem": "lem"
        };
        for (var val in array) {
            return text.replace(/\\begin{array[val]}([\s\S]*?)\\end{array[val]}/g, function(wholeMatch, m1) {
                return '<div class="latex_"' + array[val] + '>' + m1 + '</div>';
            });
        };
    });
};
};
你可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

类似(未经测试):

   converter.hooks.chain("preConversion", function(text) {
        return text.replace(/\\begin{(thm|lem)}([\s\S]*?)\\end{\1}/g, function(wholeMatch, m1, m2) {
            return '<' + m1 + '>' + m2 + '</' + m1 + '>';
        });
    });
    converter.hooks.chain("preBlockGamut", function(text, blockGamutHookCallback) {
        return text.replace(/<(thm|lem)>([\s\S]*?)<\/\1>/g, function(wholeMatch, m1, m2) {
            return '<div class="latex_' + m1 + '">' + blockGamutHookCallback(m2) + '</div>';
        });
    });