比如我html结构
<div style="color:red">colorred div </div>
<span style="color:green">colorgreen</span>
<img style="color:black"/>colorblack
<div>div div div </div>我匹配的内容是color的话,能得到文本里的3个color (注意,匹配的东西不属于html标签)
如果我匹配的是div的话,能得到第一个文本里的div 和最后一个html标签的3个div(注意,匹配的东西不属于html标签)
我自己写半天,没写出来。

解决方案 »

  1.   

    比如上面那个html,我要找出所有的字符div.(这个字符不是html标签,不是它的属性,是文本)
    然后替换成hello
    给懂了?
      

  2.   

    str='>'+str+'<';
    str=str.replace(/>[^<>]*color[^<>]*</gi,function (arg0){
    return arg0.replace(/color/gi,'hello');
    });
    str=str.replace(/^>|<$/g,'');
    alert(str);
    //只是替换color的 比较死板 具体还得看你有啥额外需求》?
      

  3.   

    <div id=a>
    <div style="color:red">colorred div </div>
    <span style="color:green">colorgreen</span>
    <img style="color:black"/>colorblack
    <div>div div div </div> 
    </div>
    <script type="text/javascript">
    var keyword = "color"
    var html = document.getElementById("a").innerHTML;
    var regex = />[^><]+(?!>)|[^><]+(?!>)</gi
    html = html.replace(regex,function(w)
    {
       return w.replace(new RegExp("\\b\\w*"+keyword+"\\w*\\b","ig"),"hello")
    })alert(html)
    </script>