最简单的方法是,IMO将内部div的内容用两边模糊的字符串包装起来,然后在整个段落上使用正则表达式来查找添加的标记以及两边所需的字符数。像这样:
var full, result,
// textContent for w3 compliance, innerText for IE
txt = "textContent" in document.body ? "textContent" : "innerText",
// Get references to both divs and store the current text of `xyz`
out = document.getElementById("outer"),
xyz = document.getElementById("xyz"),
old = xyz[txt];
// wrap the inner text with something we can easily search for:
xyz[txt] = "||||" + xyz[txt] + "||||";
// Get the whole text, change the DOM text back to what it was
full = out[txt];
xyz[txt] = old;
// Find the text with our markers and surrounding text:
result = /.{0,10}\|{4}.*?\|{4}.{0,10}/.exec(full);
alert(result[0]);
// -> "ch button ||||will highlight all|||| the words"
// Finally, replace your wrapping strings:
result = result[0].replace(/\|{4}/g, "");
alert(result);
// -> "ch button will highlight all the words"
您可能需要稍微调整regex,使其匹配,例如,内部字符串前后的两个整词。
例子
http://www.jsfiddle.net/Sy4rT/