开发者

jquery highlight certain section of text

My team has come to conclusion that in order to highlight certain text we will use !!! as special symbol. Long story.

I love !!!JavaScript and jQuery!!!.

should get transformed into

I love <span class='hl'>JavaScript and jQuery</span>.

Do not worry about the edge cases. We are developing a system for school children and they don't have complex tex开发者_如何学Ct with lots of bangs.

How do I do that?

Bonus question: After the span is applied then I was going to use jQuery higlighter plugin to highlight that code. Any suggestion in that direction.


replace in Javascript only replaces the first occurrence of a string, so you can put this feature to good use and do this:

var mytext = "I love !!!Javascript and jQuery!!!. Ya, !!!jQuery!!! rocks!";

while(true) {
    if (mytext.indexOf('!!!') == -1) break;
    mytext = mytext.replace('!!!', '<span class="hl">');
    mytext = mytext.replace('!!!', '</span>');
}
alert(mytext);

Output:
I love <span class="hl">Javascript and jQuery</span>. Ya, <span class="hl">jQuery</span> rocks!


You don't even need jQuery for this -- you can do it with javascript's build in string replace function:

var s = 'I love !!!JavaScript and jQuery!!!. Even with multiple !!!occurrences!!!.';
var replaced = s.replace(/!!!(.+?)!!!/g, function(match, text)
    {
        return '<span class="hl">' + text + '</span>'; 
    }
);

This form of the replace function accepts a regular expression and a function used to determine the replacement string. The parameters to the function are the full match (eg '!!!Javascript and jQuery!!!'), then each portion of the match that corresponds to each parametrized component of the regular expression (in this case there's only one).

NB (just in case): the ? in the regular expression makes the .+ match lazy, so that you get this:

I love <span class="highlight">JavaScript and jQuery</span>. Even with multiple <span class="highlight">occurrences</span>.

instead of this:

I love <span class="highlight">JavaScript and jQuery!!!. Even with multiple !!!occurrences</span>.


I think for this problem, you will need the contents() function in jQuery which will select all children of your selector, including text. You can read an example of how someone used it here: Only select text node without DOM.

The difficulty you're going to have is that you need the odd !!!'s to be replaced with and the even !!!'s to be replaced with . Fortunately, jQuery has selectors for odds and evens which should allow you to do that as well.


For a jQuery text highlight plugin you may want to consider http://www.frightanic.com/2011/02/27/lenient-jquery-highlight-plugin-javascript/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜