使用正则表达式添加特定单词的span类

时间:2014-07-24 20:42:25

标签: javascript html regex string

<div id="mytext">
"Albert" Einstein German: 14 March 1879 – 18 April 1955 was a German-born theoretical physicist.
He developed the general theory of "relativity", one of the two pillars of modern physics (alongside quantum mechanics). 
He is best known in popular culture for "his" mass–energy equivalence formula "E = mc2" (which has been dubbed "the world's most famous equation").
</div>

我希望在“”中使用javascript regexp

添加span类
<div id="mytext">
<span class="myclass">"Albert"</span> Einstein German: 14 March 1879 – 18 April 1955 was a German-born theoretical physicist.
He developed the general theory of <span class="myclass">"relativity"</span>, one of the two pillars of modern physics (alongside quantum mechanics). 
He is best known in popular culture for <span class="myclass">"his"</span> mass–energy equivalence formula <span class="myclass">"E = mc2"</span (which has been dubbed the world's most famous equation).
</div>

2 个答案:

答案 0 :(得分:3)

这是一个普通的JS方式和jQuery方式:

的jQuery

$("#mytext").html( $("#mytext").text().replace(/("[^"]*")/g,"<span>$1</span>") )

的JavaScript

var text = document.getElementById('mytext').innerHTML;
document.getElementById('mytext').innerHTML = text.replace(/("[^"]*")/g,"<span>$1</span>")

答案 1 :(得分:0)

几次回答。

http://jsfiddle.net/59Nrk/

〔实施例:

$.fn.highlight = function (str, className) {
    var regex = new RegExp("\\b"+str+"\\b", "gi");

    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    });
};

// Shorthand for $( document ).ready()
$(function() {
    var $txtBlock = $('#mytext'),
        highlightClass = 'myclass';
    $txtBlock.highlight('Einstein', highlightClass);
    $txtBlock.highlight('relativity', highlightClass);
    $txtBlock.highlight('his', highlightClass);

});

Highlight a word with jQuery