onivi
onivi

Reputation: 1348

How can I get all "p" except <p> tags -javascript

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

Answers (3)

Shadow Wizzard
Shadow Wizzard

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");
    }
};

Live test case.

From what I've seen, it's supported by all modern browsers and even IE9.

Upvotes: 1

Praveen
Praveen

Reputation: 56539

Try exact match in regex.

var re = new RegExp(/^p$/,"g")

Upvotes: 2

knes
knes

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

Related Questions