JavaScript,高级.replace()

时间:2013-01-27 21:20:54

标签: javascript text replace emoticons

function changeText(getString){
    var smiles_from_to = new Array();
    smiles_from_to[":)"] = "ab"; smiles_from_to[":-)"] = "ab";
    smiles_from_to[":("] = "ac"; smiles_from_to[":-("] = "ac";
    smiles_from_to["B)"] = "af"; smiles_from_to["B-)"] = "af";
    smiles_from_to[";("] = "crygirl2"; smiles_from_to[";-("] = "crygirl2";
    smiles_from_to[":-*"] = "aw"; smiles_from_to[":*"] = "aw";
    smiles_from_to[":D"] = "ag"; smiles_from_to[":-D"] = "ag";
    smiles_from_to["(devil)"] = "aq"; smiles_from_to["(wtf)"] = "ai";
    smiles_from_to["(sos)"] = "bc"; smiles_from_to["(boom)"] = "bb";
    smiles_from_to["(rofl)"] = "bj"; smiles_from_to["xD"] = "bj";
    smiles_from_to["(music)"] = "ar"; smiles_from_to["(angel)"] = "aa";
    smiles_from_to["(beer)"] = "az"; smiles_from_to["(omg)"] = "bu";
    smiles_from_to["(dance)"] = "bo"; smiles_from_to["(idiot)"] = "bm";
    smiles_from_to["(clap)"] = "bi"; smiles_from_to["(gotkiss)"] = "as";
    var replaced = getString;
    for(var key in smiles_from_to){
       replaced = replaced.replace(key, "<img src='"+chrome.extension.getURL("images/"+smiles_from_to[key]+".gif")+"' />");
    }
    return replaced;
}

大家好,我需要为更简单的事情优化代码,所以尽量避免for循环.. “var replacement”是一个巨大的HTML代码(div的内容包含100行消息,包含日期,用户名,userinfo(工具提示),消息,.....) 此代码是我的Chrome扩展程序中的一部分。所以我不能在php方面做到这一点。

1 个答案:

答案 0 :(得分:1)

您可以使用/:\)|:\(|.../g形式的单个巨型正则表达式,然后传递一个回调函数作为查找对象中的匹配项的替代品。