您现在的位置是:首页 > 其他

李清波 2017-03-13 其他 1892 复制当前网址

JavaScript高亮关键字文本

有很多jQuery插件可以实现文本高亮,这里使用一个简单的方法,实现高亮,不需要其他JavaScript包,只是纯净的JavaScript,这个脚本返回被处理的原始数据,高亮的文本用标签包含起来,可以使用css定义样式。

function highlight(text, words, tag) {
    // 默认的标签,如果没有指定,使用span
    tag = tag || 'span';
    var i, len = words.length, re;
    for (i = 0; i < len; i++) {
        // 正则匹配所有的文本
        re = new RegExp(words[i], 'g');
        if (re.test(text)) {
            text = text.replace(re, '<'+ tag +' class="highlight">$&</'+ tag +'>');
        }
    }
    return text;
}



将高亮文本还原

function unhighlight(text, tag) {
    // 默认的标签,如果没有指定,使用span
    tag = tag || 'span';
    var re = new RegExp('(<'+ tag +'.+?>|<\/'+ tag +'>)', 'g');
    return text.replace(re, '');
}



使用方法:

$('p').html( highlight(
    $('p').html(), //替换的文本
    ['foo', 'bar', 'baz', 'hello world'], //高亮的文本数组
    'strong' //自定义标签
));



文章来源:http://liqingbo.com/blog-1298.html

评论