Search code examples
htmljquerydomtextreplace

How can I use global regex to replace all instances of something without breaking other Javascript functions?


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!

EDIT: To clarify, Airtable is my headless CMS. Data for the website is pulled from Airtable. Airtable has rich-text fields (where my client writes his page content), but the Airtable API automatically prefixes http:// to any links. Any relative links, for example /about-us, are turned into http:///about-us because of this. So the issue is with links inside of href attributes. Not sure if this context is relevant, but I thought I’d add it anyway.


Solution

  • 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>