Reputation: 1348
I am trying to replace all "p" with x.
var re = new RegExp("p","g");
document.body.innerHTML=document.body.innerHTML.replace(re, "x");
But this code line replaces all "p" letters and paragraph tags with x.
Before:
p and <p>
After:
x and <x>
How can I replace only p letters (not a tag)?
Upvotes: 0
Views: 228
Reputation: 66398
Based on the great answer to this question, you can grab all text nodes in the document with such a code, then iterate over them and change their value:
window.onload = function() {
var walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_TEXT,
null,
false
);
var node;
var textNodes = [];
while(node = walker.nextNode()) {
textNodes.push(node);
}
var regex = new RegExp("p","g");
for (var i = 0; i < textNodes.length; i++) {
var node = textNodes[i];
node.nodeValue = node.nodeValue.replace(regex, "x");
}
};
From what I've seen, it's supported by all modern browsers and even IE9.
Upvotes: 1
Reputation: 883
try this:
var re = new RegExp(/(?<!<)p(?!>)/,"g");
beware of </p>
also, if you want to consider all <p class...
tags, you should use more complicated regex.
Upvotes: 1