您如何突出显示页面上与一组单词匹配的所有单词? [英] How do you highlight all the words on the page that match an array of words?

查看:28
本文介绍了您如何突出显示页面上与一组单词匹配的所有单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的网页上找到与 Javascript 数组中的任何单词匹配的所有单词,并突出显示它们(将它们包装在特殊的 span 标签中).什么是最简单的方法来做到这一点?我使用jquery.

I want to find all the words on my webpage that match any of the words in a Javascript array, and highlight them (wrap them in special span tags). What's the easiest way to do this? I use jquery.

推荐答案

不完美,但简单且可行:

Not perfect, but simple and may work:

var regex = /(Hello|Goodbye)/g;

$('*').each(function() {
    var $this = $(this);
    var text = $this.text();
    if (regex.test(text)) {
        $this.html(
            $this.html().replace(regex, '<span>$1</span>')
        );
    }
});

http://jsfiddle.net/pdWAn/

这篇关于您如何突出显示页面上与一组单词匹配的所有单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆