我有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也没有产生任何结果,还有其他有效的方法可以解决我想要解决的问题吗?
答案 0 :(得分: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, ''));
答案 1 :(得分: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);
答案 2 :(得分:0)
你可以做这样的事情
var obj1Txt= $(obj1).text();
var obj2txt= $(obj2).text();
var output= '<p>'+obj1txt.replace(obj2txt,'')+'</p>';
答案 3 :(得分:-1)
您可以尝试使用$ .html()
匹配字符串表示return obj1.clone().html(obj1.html().replace(obj2.html(), ''))