2

我有 2 个具有以下内容的节点集;

obj1 "<p>the quick <b>brown</b> fox jumped over the fence</p>"
obj2 "<p>the quick <b>brown</b> fox </p>"

我试图将 obj1 的内容与 obj2 匹配,然后删除匹配的节点以留下一个看起来像的对象。

output "<p>jumped over the fence</p>"

使用 jquery $.match 返回一个错误并且 $.find 也没有产生任何结果,还有其他有效的方法来做我想要解决的问题吗?

4

4 回答 4

2

不确定这是否符合要求,但变量对我来说看起来像 HTML 字符串,看起来你想逐字比较字符串而不丢失原始主要元素,我会做类似的事情:

var obj1 = "<p>the quick <b>brown</b> fox jumped over the fence</p>",
    obj2 = "<p>the quick <b>brown</b> fox </p>";

var obj3 = compare(obj1, obj2);

$('body').append(obj3);


function compare(elm1, elm2) {
    var obj = [],
        o1 = String($(elm1).html()).split(' '), //get <p>'s inner HTML as string and split on spaces to get each word
        o2 = String($(elm2).html()).split(' ');

    $.each(o1, function(i,e) { //iterate over each word inside <p> of first string
        if (e !== o2[i]) obj.push(e); //check if matches each word in the same loaction in the second string
    });
    //we should now have an array of the words that does not match each other
    return $(elm1).clone().html(obj.join(' ')); //join with new spaces and return the string as html contained in a clone of the original element.
}

小提琴

FIDDLE作为函数调用(看起来更简单)!

应该补充一点,这不适用于以下内容:

var obj1 = "<p>the quick <b>brown</b> fox jumped over the fence</p>",
    obj2 = "<p>fox jumped over the fence</p>";

由于这些字符串不是逐字匹配的,尽管第二个是第一个等的一部分,但是在这种情况下要删除字符串的相似部分,您总是可以这样做:

var obj1 = "<p>the quick <b>brown</b> fox jumped over the fence</p>",
    obj2 = "<p>fox jumped over the</p>",
    o1 = String($(obj1).html()),
    o2 = String($(obj2).html());

var obj = $(obj1).clone().html(o1.replace(o2, ''));

小提琴

于 2012-08-21T20:13:01.723 回答
1

只是快速刺一下。也许这有帮助。它将在 HTML 中保留粗体标记,并且可能不会涵盖您直接问题之外的任何内容。

var obj1 = "<p>the quick <b>brown</b> fox jumped over the fence</p>";
var obj2 = "<p>the quick <b>brown</b> fox </p>";

var result="";
var inTag=false;

for (i=0;i<obj1.length;i++)
{
    if(obj1[i]=='<')
        isTag=true;
    if(!isTag)
    {
        if(i<obj2.length-1)
        {
            if(obj1[i]!=obj2[i])
            {
                result+=obj1[i];
            }
        }
        else
        {
            result+=obj1[i];
        }
    }
    else
    {
        result+=obj1[i];
    }
    if(obj1[i]=='>')
        isTag=false;
}

$("#result").html(obj1+obj2 + "<p>Difference:</p>"+result);​

http://jsfiddle.net/8qYV4/1/

于 2012-08-21T20:11:27.077 回答
0

你可以做这样的事情

var obj1Txt= $(obj1).text();
var obj2txt= $(obj2).text();
var output= '<p>'+obj1txt.replace(obj2txt,'')+'</p>';
于 2012-08-21T20:12:08.640 回答
-1

您可以尝试使用 $.html() 匹配字符串表示

return obj1.clone().html(obj1.html().replace(obj2.html(), ''))
于 2012-08-21T20:06:48.587 回答