你最好的選擇,而且更容易了很多比它聽起來,是不是要嘗試使用正則表達式解析HTML,但採取的事實是t優勢他的DOM已經和遞歸地處理文本節點。
這裏是一個臨時的:Live Example | Source
// We use this div's `innerHTML` to parse the markup of each replacment
var div = document.createElement('div');
// This is the recursive-descent function that processes all text nodes
// within the element you give it and its descendants
function doReplacement(node, rex, text) {
var child, sibling, frag;
// What kind of node did we get?
switch (node.nodeType) {
case 1: // Element
// Probably best to leave `script` elements alone.
// You'll probably find you want to add to this list
// (`object`, `applet`, `style`, ...)
if (node.nodeName.toUpperCase() !== "SCRIPT") {
// It's an element we want to process, start with its
// *last* child and work forward, since part of what
// we're doing inserts into the DOM.
for (child = node.lastChild; child; child = sibling) {
// Before we change this node, grab a reference to the
// one that follows it
sibling = child.previousSibling;
// Recurse
doReplacement(child, rex, text);
}
}
break;
case 3: // Text
// A text node -- let's do our replacements!
// The first two deal with the fact that the text node
// may have less-than symbols or ampersands in it.
// The third, of course, does your replacement.
div.innerHTML = node.nodeValue
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(rex, text);
// Now, the `div` has real live DOM elements for the replacement.
// Insert them in front of this text node...
insertChildrenBefore(div, node);
// ...and remove the text node.
node.parentNode.removeChild(node);
break;
}
}
// This function just inserts all of the children of the given container
// in front of the given reference node.
function insertChildrenBefore(container, refNode) {
var parent, child, sibling;
parent = refNode.parentNode;
for (child = container.firstChild; child; child = sibling) {
sibling = child.nextSibling;
parent.insertBefore(child, refNode);
}
}
,你會打電話來是這樣的:
doReplacement(document.body,
/MyName/g,
"<span><span class='myName'>MyNameReplace</span></span>");
強制性http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained - 標籤 –
*「我如何修改正則表達式,以便它只能在HTML內容中找到它?」*可靠嗎?你不能。 –
可能重複的[在JavaScript中,我如何替換HTML頁面中的文本而不影響標籤?](http://stackoverflow.com/questions/1444409/in-javascript-how-can-i-replace-text- in-an-html-page-without-affecting-the-tags) – Barmar