Javascript HTML关键字突出显示

时间:2014-01-28 16:45:23

标签: javascript html css

<div id="abc">
    Lorem Ipsum is simply dummy class highlight text class that needs to be highlighted.
</div>

我想强调一下这些词:&#34;课堂亮点&#34;和&#34; class&#34;

var words = ["class highlight", "class"];
var replace = '<span class="highlight-text">$1</span>';
var x = document.getElementById("abc").innerHtml;

for(var i = 0; i<words.length; i++){
    document.getElementById("abc").innerHtml.replace(pattern, replace);
}

问题是第一次,它正确替换。但第二次,它也吐出了HTML,并强调了这一点。我理解为什么会发生这种情况,但会解决这个问题。

编辑: 对不起,我忘了包括:pattern = words [i]

2 个答案:

答案 0 :(得分:0)

这会更好:

var words = ["class highlight", "class"];
var replace = '<span class="highlight-text">$1</span>';
var x = document.getElementById("abc").innerHtml;

for(var i = 0; i<words.length; i++){
    var rpl = replace.replace('$1', words[i]);
    document.getElementById("abc").innerHtml.replace(words[i], rpl);
}

答案 1 :(得分:0)

var words = [ "class", "class highlight"];

//replace reg exp will be in 3 parts
var replace = '$1<span class="highlight-text">$2</span>$3';

//need the longer words to appear before the smaller
words.sort(function(a,b){ return b.length>a.length; });  

//us an OR expression to replace the words
var re = new RegExp("([$\\s])(" + words.join("|") + ")([\\s^])","gi");


var elem = document.getElementById("abc");

//grab the text since matching on HTML is bad
var txt = elem.innerText || elem.textContent;

//make the new string
var replacedText = txt.replace(re, replace);

elem.innerHTML = replacedText;