skip to Main Content

I’m trying to replace all instances of http:/// on my website with / using global regex like this:

$('body').html($('body').html().replace(/http:////g,'/'));

It works well, but unfortunately this somehow breaks all the other Javascript-bound events and functions I have on my website.

Does someone know of a way to achieve the same without breaking the other functions?

I tried to find other ways of using global regex but I’m guessing this somehow messes with the DOM, so not sure how to fix this.

Thank you!

2

Answers


  1. Instead of replacing the HTML content directly, you can traverse the DOM and update the specific text nodes that contain the target string:

    // Define a function to update the text nodes recursively
    function updateTextNodes(node) {
      if (node.nodeType === Node.TEXT_NODE) {
        node.nodeValue = node.nodeValue.replace(/http:////g, '/');
      } else {
        node.childNodes.forEach(updateTextNodes);
      }
    }
    
    // Find all text nodes within the body and update their values
    $('body').contents().each(function() {
      updateTextNodes(this);
    });
    
    Login or Signup to reply.
  2. Chnaging the innerHTML removes all the event listeners bound. So I would just alter the content that has the issues directly. If it is links, select all the links with the problem and replace them attribute.

    document.querySelectorAll('a[href^="http:///"]').forEach(link => link.href = link.href.substr(7))
    <a href="http:///example1">test</a>
    <a href="http:///example2">test</a>
    <a href="http:///example3">test</a>
    <a href="http:///example4">test</a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search