Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to select every text word that is text but not HTML or code

Trying to find all words within a specific tag like all p tags, so that I can apply some regex to it and replace all the words.

For example,

<p>the lazy cat went <div>up</div> to the cheery fox</p>

You can choose an "all words" regex:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

/\w+/g

You can use a jquery replace. Here’s my code that not fully working yet.

$("p").html($("p").html().replace(/\w+/g, 'fox'));

Now what I need to do is get it to work, so that all the words inside the p tag are replaced with another word. Result:

<p>fox fox fox fox <div>fox</div> fox fox fox fox</p>

How can I get jquery to replace all individual words that are inside a p tag, but not affect any other HTML or code inside it?

>Solution :

Retrieve all text nodes instead, and iterate over them to reassign their content to the replaced string.

const getAllTextNodes = (parent) => {
    const walker = document.createTreeWalker(
        parent,
        NodeFilter.SHOW_TEXT,
        null,
        false
    );
    let node;
    const textNodes = [];
    while(node = walker.nextNode()) {
        textNodes.push(node);
    }
    return textNodes;
};
for (const p of $('p')) {
  for (const textNode of getAllTextNodes(p)) {
    textNode.textContent = textNode.textContent.replace(/\w+/g, 'fox');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>the lazy cat went up to the cheery fox</p>

Or ditch jQuery, since it’s not really providing any benefit

const getAllTextNodes = (parent) => {
    const walker = document.createTreeWalker(
        parent,
        NodeFilter.SHOW_TEXT,
        null,
        false
    );
    let node;
    const textNodes = [];
    while(node = walker.nextNode()) {
        textNodes.push(node);
    }
    return textNodes;
};
for (const p of document.querySelectorAll('p')) {
  for (const textNode of getAllTextNodes(p)) {
    textNode.textContent = textNode.textContent.replace(/\w+/g, 'fox');
  }
}
<p>the lazy cat went up to the cheery fox</p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading