日期:2014-05-16  浏览次数:20399 次

javascript 替换对象
var str1="北京abccc北京abc,fdsaf北京"
需要替换 为str2="<font style='background-color:#ffff00'>北京</font>abccc<font style='background-color:#ffff00'>北京</font>abc,fdsaf<font style='background-color:#ffff00'>北京</font>"
如何处理呀?

------解决方案--------------------
HTML code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>NewDocument</title>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />
        <meta name="generator" content="Editplus" />
        <meta name="author" content="" />
        <meta name="keywords" content="" />
        <meta name="description" content="" />
    </head>
    <body>
        <input type="text" id="search" onkeyup="searchDate()"/>
        <div id="cnt">a只是一个简单的例子,如用csdn的替换的,如将cSdn,CSdn,CSDN等 这种组合全部给增加font,但是里面的原有的字母是不能改变的</div>
        <script type="text/javascript">
            var cacheData = cnt.innerHTML;
            var searchDate = function () {
                var key  = document.getElementById("search").value;
                var patten = new RegExp("("+key+")","gi");
                document.getElementById("cnt").innerHTML = cacheData.replace(patten,"<i style='color:red'>$1</i>");
            };
        </script>
    </body>
</html>