在HTML中查找单词 [英] Find word in HTML

查看:122
本文介绍了在HTML中查找单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在HTML字符串中找到给定的单词并在其周围添加一个范围。

I am trying to find given word in HTML string and add a span around it.

我现在正在做的是:

function find(what:String,where:String)
{
    var regexp:RegExp=new RegExp(what,'gi');
    return where.replace(regexp,'<span>$&</span>');
}

它适用于不在HTML标签内的单词。
我想要的是忽略HTML标签内的那些。

It works well on words that are not inside HTML tags. What I want is to ignore those that are inside HTML tags.

示例: find(spain)

输入:

Example: find("spain")
Input:

The rain in <b class="spain">Spain</b> stays mainly in the <i data-test="Spain">plain</i>.

输出:

The rain in <b class="spain"><span>Spain</span></b> stays mainly in the <i data-test="Spain">plain</i>.

我怎样才能实现这个目标?

How can I achieve this, please?

推荐答案

要考虑可以匹配的html标签和属性,您需要以这种或那种方式解析该HTML。最简单的方法是将其添加到DOM(或仅添加到新元素):

To account for html tags and attributes that could match, you are going to need to parse that HTML one way or another. The easiest way is to add it to the DOM (or just to a new element):

var container = document.createElement("div");
container.style.display = "none";
document.body.appendChild(container);  // this step is optional
container.innerHTML = where;

解析后,您现在可以使用DOM方法迭代节点,只找到文本节点并搜索那些。使用递归函数来遍历节点:

Once parsed, you can now iterate the nodes using DOM methods and find just the text nodes and search on those. Use a recursive function to walk the nodes:

function wrapWord(el, word)
{
    var expr = new RegExp(word, "i");
    var nodes = [].slice.call(el.childNodes, 0);
    for (var i = 0; i < nodes.length; i++)
    {
        var node = nodes[i];
        if (node.nodeType == 3) // textNode
        {
            var matches = node.nodeValue.match(expr);
            if (matches)
            {
                var parts = node.nodeValue.split(expr);
                for (var n = 0; n < parts.length; n++)
                {
                    if (n)
                    {
                        var span = el.insertBefore(document.createElement("span"), node);
                        span.appendChild(document.createTextNode(matches[n - 1]));
                    }
                    if (parts[n])
                    {
                        el.insertBefore(document.createTextNode(parts[n]), node);
                    }
                }
                el.removeChild(node);
            }
        }
        else
        {
            wrapWord(node, word);
        }
    }
}

这是一个有效的演示:< a href =http://jsfiddle.net/gilly3/J8JJm/3 =nofollow> http://jsfiddle.net/gilly3/J8JJm/3

Here's a working demo: http://jsfiddle.net/gilly3/J8JJm/3

这篇关于在HTML中查找单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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