不确定这是否符合要求,但变量对我来说看起来像 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, ''));
小提琴