简体   繁体   English

我如何获得除“ p”以外的所有“ p” <p> 标签-javascript

[英]How can I get all “p” except <p> tags -javascript

I am trying to replace all "p" with x. 我正在尝试用x替换所有“ p”。

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. 但是此代码行用x替换了所有“ p”字母和段落标签。

Before: 之前:

p and <p>

After: 后:

x and <x>

How can I replace only p letters (not a tag)? 如何只替换p个字母(不替换标签)?

regex尝试完全匹配

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

try this: 尝试这个:

var re = new RegExp(/(?<!<)p(?!>)/,"g");

beware of </p> 提防</p>

also, if you want to consider all <p class... tags, you should use more complicated regex. 另外,如果要考虑所有<p class...标记,则应使用更复杂的正则表达式。

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. 据我了解,所有现代浏览器甚至IE9都支持它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM