如果你想完全匹配“超人”而不是包含它的东西,你可以做这样的事情。
HTML
<div>
<p>Superman and some other text</p>
</div>
<div>
<p>More Superman and some other text</p>
</div>
<div>
<p>Something Supermanish and some other text</p>
</div>
Javascript
function walkTheDOM(node, func) {
func(node);
node = node.firstChild;
while (node) {
walkTheDOM(node, func);
node = node.nextSibling;
}
}
function escapeRegex(string) {
return string.replace(/[\[\](){}?*+\^$\\.|]/g, "\\$&");
}
function replaceText(node, searchText, replaceText) {
var textNodes = [],
length,
i;
function filterTextNodes(currentNode) {
if (currentNode.nodeType === 3) {
textNodes.push(currentNode);
}
}
walkTheDOM(node, filterTextNodes);
i = 0;
length = textNodes.length;
while (searchText && i < length) {
textNodes[i].nodeValue = textNodes[i].nodeValue.replace(new RegExp("\\b" + escapeRegex(searchText) + "\\b"), replaceText);
i += 1;
}
}
var query = {
alt_name: "Giggitty",
test: "brand",
old: "Superman",
new: "Batman"
};
if (query.test === "brand") {
replaceText(document, query.old, query.new);
}
在jsfiddle 上