s = s.indexOf("text-indent") == -1?'<p>':'<p style = "text-indent: 2em;">';最针对性,又有点那啥的方法,就是直接判断就行了。var s = '<p asdfas style="line-height: 150%; tex1t-indent: 2em; mso-char-indent-count: 2.0">';
var reg = /\<p[^\>]*(\s+style=\"([^\"]*)\")[^\>]*\>/g;
s = s.replace(reg,function($1,$2,$3){
if($2.indexOf("text-indent") == -1){
return $1.replace($2,"");
}else{
return $1.replace($3,"text-indent: 2em;");
}
});
console.log(s);正则的话,这样就会只对style做处理,如果p中有其他的属性的话,就保留其他属性。试试看,这里是把目的当做字符串处理的。
如果你是要使用工具对文件中进行替换,把其中的转义字符的反斜杠去掉就可以使用了。试试行不。

解决方案 »

  1.   


    function replacep(str){
        var reg=/^(<p style\b.*)(text-indent:[^;]+;)(.*>)$/g;    if(reg.test(str)){
            return str.replace(reg, "$1text-indent: 2em;$3");
        }
        else{
            return "<p>";
        }
    }var canMatchedStr="<p style=\"line-height: 150%; text-indent: 2em; mso-char-indent-count: 2.0\">";
    var cannotMatchedStr="<p style=''>";alert(replacep(canMatchedStr)); //<p style="line-height: 150%; text-indent: 3em; mso-char-indent-count: 2.0">
    alert(replacep(cannotMatchedStr)); //<p>
      

  2.   

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <script type="text/javascript">
    window.onload=function(){
    var ps=document.getElementsByTagName("p");
    for(var i=0;i<ps.length;i++){
    if(ps[i].style.textIndent){
    ps[i].style.textIndent='2em';
    }
    }
    }
    </script>
    </head><body>
      <p style="line-height: 150%; text-indent: 2em; mso-char-indent-count: 2.0">123</p>
        <p style="line-height: 150%; mso-char-indent-count: 2.0">456</p>
        <p style="line-height: 150%; text-indent: 3em; mso-char-indent-count: 2.0">123</p>
    </body>
    </html>如果是字符串的话可以用正则  但如果是dom节点的话感觉操作dom方便点