Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9050797
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T12:44:38+00:00 2026-06-16T12:44:38+00:00

I have javascript code that works pretty well like: var rgx = /MyName/g; var

  • 0

I have javascript code that works pretty well like:

var rgx = /MyName/g;
var curInnerHTML = document.body.innerHTML;
curInnerHTML = curInnerHTML.replace(rgx, "<span><span class='myName'>MyNameReplace</span></span>");

The problem is that its matching the regex even in scenarios where it is contained within HTML attributes and what-not. How can I modify the regex so that it will only find it within the content of the HTML? For example, in this string

    <div class="someclass" title="MyName">
MyName
</div>

it currently results like (note the change in the title attribute):

        <div class="someclass" title="<span><span class='myName'>MyNameReplace</span</span>">
<span><span class='myName'>
    MyNameReplace</span></span>
    </div>

But I need it to be (leave the title attribute untouched):

    <div class="someclass" title="MyName">
<span><span class='myName'>MyNameReplace</span></span>
</div>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T12:44:39+00:00Added an answer on June 16, 2026 at 12:44 pm

    Your best bet, and it’s a lot easier than it sounds, is not to try to use regex to parse HTML, but to take advantage of the fact that the DOM already has and recursively process the text nodes.

    Here’s an off-the-cuff:

    // We use this div's `innerHTML` to parse the markup of each replacment
    const div = document.createElement('div');
    
    // This is the recursive-descent function that processes all text nodes
    // within the element you give it and its descendants
    function doReplacement(node, rex, text) {
        // What kind of node did we get?
        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                // Probably best to leave `script` elements alone.
                // You'll probably find you want to add to this list
                // (`object`, `applet`, `style`, ...)
                if (node.nodeName.toUpperCase() !== "SCRIPT") {
                    // It's an element we want to process, start with its
                    // *last* child and work forward, since part of what
                    // we're doing inserts into the DOM.
                    let sibling;
                    for (const child = node.lastChild; child; child = sibling) {
                        // Before we change this node, grab a reference to the
                        // one that precedes it
                        sibling = child.previousSibling;
    
                        // Recurse
                        doReplacement(child, rex, text);
                    }
                }
                break;
            case Node.TEXT_NODE:
                // A text node -- let's do our replacements!
                // The first two deal with the fact that the text node
                // may have less-than symbols or ampersands in it.
                // The third, of course, does your replacement.
                div.innerHTML = node.nodeValue
                                    .replace(/&/g, "&amp;")
                                    .replace(/</g, "&lt;")
                                    .replace(rex, text);
    
                // Now, the `div` has real live DOM elements for the replacement.
                // Insert them in front of this text node...
                insertChildrenBefore(div, node);
                // ...and remove the text node.
                node.parentNode.removeChild(node);
                break;
        }
    }
    
    // This function just inserts all of the children of the given container
    // in front of the given reference node.
    function insertChildrenBefore(container, refNode) {
        let sibling;
        const parent = refNode.parentNode;
        for (const child = container.firstChild; child; child = sibling) {
            sibling = child.nextSibling;
            parent.insertBefore(child, refNode);
        }
    }
    

    Which you’d call like this:

    doReplacement(
        document.body,
        /MyName/g,
        "<span><span class='myName'>MyNameReplace</span></span>"
    );
    

    Live Example:

    // We use this div's `innerHTML` to parse the markup of each replacment
    const div = document.createElement('div');
    
    // This is the recursive-descent function that processes all text nodes
    // within the element you give it and its descendants
    function doReplacement(node, rex, text) {
        // What kind of node did we get?
        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                // Probably best to leave `script` elements alone.
                // You'll probably find you want to add to this list
                // (`object`, `applet`, `style`, ...)
                if (node.nodeName.toUpperCase() !== "SCRIPT") {
                    // It's an element we want to process, start with its
                    // *last* child and work forward, since part of what
                    // we're doing inserts into the DOM.
                    let sibling;
                    for (let child = node.lastChild; child; child = sibling) {
                        // Before we change this node, grab a reference to the
                        // one that precedes it
                        sibling = child.previousSibling;
    
                        // Recurse
                        doReplacement(child, rex, text);
                    }
                }
                break;
            case Node.TEXT_NODE:
                // A text node -- let's do our replacements!
                // The first two deal with the fact that the text node
                // may have less-than symbols or ampersands in it.
                // The third, of course, does your replacement.
                div.innerHTML = node.nodeValue
                                    .replace(/&/g, "&amp;")
                                    .replace(/</g, "&lt;")
                                    .replace(rex, text);
    
                // Now, the `div` has real live DOM elements for the replacement.
                // Insert them in front of this text node...
                insertChildrenBefore(div, node);
                // ...and remove the text node.
                node.parentNode.removeChild(node);
                break;
        }
    }
    
    // This function just inserts all of the children of the given container
    // in front of the given reference node.
    function insertChildrenBefore(container, refNode) {
        let sibling;
        const parent = refNode.parentNode;
        for (let child = container.firstChild; child; child = sibling) {
            sibling = child.nextSibling;
            parent.insertBefore(child, refNode);
        }
    }
    
    setTimeout(() => {
        doReplacement(
            document.body,
            /MyName/g,
            "<span><span class='myName'>MyNameReplace</span></span>"
        );
    }, 800);
    <p>MyName</p>
    <p>This is MyName in a sentence.</p>
    <p>This is <strong>MyName nested</strong></p>
    <p>How 'bout <strong><em>making MyName nested more deeply</em></strong></p>
    <p>This is MyName in an element with &lt; and &amp; in it.</p>
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following Javascript code that works perfectly: $(document).ready(function() { $(#Select1).setDefault(); $(#Select2).setDefault(); $(#Select3).setDefault();
I have some JavaScript code that works in IE containing the following: myElement.innerText =
i have some javascript roll over code that works fine in firefox but when
I have a little bit of Javascript that almost works correctly. Here's the code:
I have webscript written in Javascript for send emails. It works pretty well, but
I have seen Javascript code that uses parenthesis immediately after a function's closing curly
I have a javascript code that have span tag and inside the span tag
I have some Javascript code that will programmatically register an COM interop assembly by
I have some javascript code that creates an img tag with a mouseover callback,
I have some Javascript code that creates 2 arrays: One for Product Category and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.