I’m facing a challenge with text replacement in JavaScript using a regular expression. Here’s a demonstration of what I’m attempting to achieve:
<html>
<head></head>
<body>
<div id="container"><a href="#" title="This was Old">This was Old</a></div>
<script>
var greeting = "Hello";
var content = document.getElementById("container").innerHTML;
var updatedContent = content.replace(/Old/g, "<div onclick='notify(\"" + greeting + "\");'>New</div>");
document.getElementById("container").innerHTML = updatedContent;
function notify(message) {
alert(message);
}
</script>
</body>
</html>
This snippet is part of a much larger application where our script is integrated into third-party HTML pages, leaving us unable to modify the actual HTML. Running this code causes the text to appear incorrectly, and removing the word “Old” from the title resolves the issue. Unfortunately, the HTML is out of my control, so I need to adjust my script to cope with this.
Is there a method to implement a regular expression that can skip replacements happening within angle brackets (“<” and “>”)? Alternatively, could you suggest another approach to tackle this?
Note: I cannot utilize the DOM for replacements since it leads to crashes on pages with extensive text content. I aim for full-page text modifications.
Thank you for your assistance!