Javascript 如何使用JS突出显示网页上的字符串列表?

Javascript 如何使用JS突出显示网页上的字符串列表?,javascript,jquery,Javascript,Jquery,我有一个文本文件,其中包含一堆未格式化的文本行: this is string 1 this is string 2 with multiple ch$r$t#rs and in-text citations[1] this is string 3 我需要使用这些字符串作为JS函数的输入,JS函数会突出显示网页上出现的每个字符串。理想情况下,有一种方法可以将文本文件传递给函数 什么函数/代码最适合用JavaScript实现这一点?这里是jQuery的“突出显示”插件,它允许您喜欢的任何输入

我有一个文本文件,其中包含一堆未格式化的文本行:

this is string 1
this is string 2 with multiple ch$r$t#rs and in-text citations[1]
this is string 3

我需要使用这些字符串作为JS函数的输入,JS函数会突出显示网页上出现的每个字符串。理想情况下,有一种方法可以将文本文件传递给函数

什么函数/代码最适合用JavaScript实现这一点?

这里是jQuery的“突出显示”插件,它允许您喜欢的任何输入

$.fn.highlight = function(pat) {
    function innerHighlight(node, pat) {
        var skip = 0;
        if (node.nodeType == 3) {
            var pos = node.data.toUpperCase().indexOf(pat);
            if (pos >= 0) {
                var spannode = document.createElement('span');
                spannode.className = 'highlight';
                var middlebit = node.splitText(pos);
                var endbit = middlebit.splitText(pat.length);
                var middleclone = middlebit.cloneNode(true);
                spannode.appendChild(middleclone);
                middlebit.parentNode.replaceChild(spannode, middlebit);
                skip = 1;
            }
        }
        else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
            for (var i = 0; i < node.childNodes.length; ++i) {
                i += innerHighlight(node.childNodes[i], pat);
            }
        }
        return skip;
    }
    return this.each(function()
        {
            innerHighlight(this, pat.toUpperCase());
        }
    );
};
$.fn.removeHighlight = function() {
    return this.find("span.highlight").each(function()
        {
            this.parentNode.firstChild.nodeName;
            with (this.parentNode) {
                replaceChild(this.firstChild, this);
                normalize();
            }
        }
    ).end();
};
我的CSS(但您可以设置自己的):


您所做的就是将整个插件代码添加到自定义JS文件中(或者创建一个
plugins.jquery.js
文件并将其包含在内。CSS放在外部样式表或页面的标题部分。好的。它可以使用简单的短语,但任何带有符号的内容都不会突出显示。此外,如何一次传递多个字符串?确保对任何符号使用HTMLentities,以便能够正确解码。例如:例如,
George&Weasey
将是
George&;Weasey
。对于多个字符串,您必须修改代码以将新行字符转换为
\n
。我尝试对字符串进行编码,但当像“maybe empty”这样的字符串高亮显示时,会出现一个“(maybe empty),[4]”没有。似乎括号和方括号没有被转义。:(我认为它实际上可能是试图将
指针作为数组输入的逗号。您必须处理代码(在测试事件之前将所有内容转换为字符串)。抱歉,我仅将其用于简单文本。
$('body').highlight(needle);
.highlight {background-color:yellow;color:black;}