如何更改包含特定单词的HTML页面中的行的颜色

时间:2014-05-22 14:26:39

标签: javascript jquery html css

如何更改HTML页面中某一行的颜色(pre>中的文本)包含一个特定的单词 例如,我想改变颜色任何一行包含" ERROR"和#34; Erreur"

2014/05/22 02:27:02 - X.0 - Finished processing 
2014/05/22 02:27:02 - DSA.0 - Finished processing 
2014/05/22 02:27:03 - Block.0 - Finished processing 
2014/05/22 02:27:03 - Errors CustomerGroupDimEU.0 
2014/05/22 02:27:03 - Old = New ?.0 - Finished processing 
2014/05/22 02:27:03 - Exists = 0.0 - Finished processing 

此代码仅替换单词

(function ($) {
    var thePage = $("body");
    thePage.html(thePage.html().replace(/Error/ig, '<span style="color: red;font-weight: bold;">Error</span>'));
})

2 个答案:

答案 0 :(得分:4)

正则表达式很棘手。但这是你想要的输出:)

 (function($) {
    var thePage = $("body"); 
    thePage.html(thePage.html().replace(/(^.*\b(Errors)\b.*)$/igm, 
     '<span style="color: red;font-weight: bold;">$1</span>'));
    })(jQuery);

如果您想匹配更多关键字:

/(^.*\b(Errors|Error|Erreur)\b.*)$/igm  

您可以继续使用|

添加关键字

<强> DEMO

答案 1 :(得分:1)

这样的事情:

<pre>2014/05/22 02:27:02 - X.0 - Finished processing </pre>
<pre>2014/05/22 02:27:02 - DSA.0 - Finished processing </pre>
<pre>2014/05/22 02:27:03 - Block.0 - Finished processing</pre>
<pre>2014/05/22 02:27:03 - Errors CustomerGroupDimEU.0 </pre>
<pre>2014/05/22 02:27:03 - Old = New ?.0 - Finished processing </pre>
<pre>2014/05/22 02:27:03 - Exists = 0.0 - Finished processing </pre>

<script>
$(document).ready(function(){
  $("pre:contains('Error')").css({"color": "red", "fontWeight": "bold"});
})
</script>