Regular express version - javascript

I am trying to replace text in javascript using a regular expression like the following [example of what I'm trying to do]:

<html><head></head>
<body>
  <div id="div1"><a href="#" title="This is Old">This is Old</a></div>
  <script> 
    var message = "Hi";
    var str = document.getElementById("div1").innerHTML;
    var newstr = str.replace(/Old/g, "<div onclick='say(\""+message+"\");'>New</div>");
    document.getElementById("div1").innerHTML = newstr;
    function say(message)
    {
      alert(message);
    }
  </script>
</body>
</html>

This is an example of the code I'm trying to make in a large application. Our script is introduced on thrid party html pages, so we do not control html. If you run this code, you will see that the text looks broken, and if you just remove the “Old” from the title tag, it will work fine. I cannot change the html, so I need to change the script to handle this.

Is there a way I can put some regular expressions that can get around replacing text if it occurs between "<" and ">"? or some other way to solve this problem.

DOM , , , .

:)

EDIT: , :)

+3
3

, . , .

EDIT:
RegEx, . , .

2:
, , .

>[^><]*(Old)[^<>]*<

3:
, >

[^><]*(Old)[^<>]*<

4:

<html><head></head>
<body>
  <div id="div1"><a href="#" title="This is Old">This is Old</a></div>
  <script> 
    var message = "Hi";
    var str = document.getElementById("div1").innerHTML;
    var newstr = str.replace(/([^><]*)Old([^<>]*<)/g, "$1<div onclick='say(\""+message+"\");'>New</div>$2");
    document.getElementById("div1").innerHTML = newstr;
    function say(message)
    {
      alert(message);
    }
  </script>
</body>
</html>
+1

:

str.replace(/(>[^<]*)Old/g, "$1<div onclick='say(\"message\");'>New</div>");

" HTML"

+1

It would not be easier to assign an id for <a> instead, and then run the same replace () on it innerHTML (which should not contain the title attribute of the tag):

<html><head></head>
<body>
  <div id="div1"><a id="link" href="#" title="This is Old">This is Old</a></div>
  <script> 
    var message = "Hi";
    var str = document.getElementById("link").innerHTML;
    var newstr = str.replace(/Old/g, "<div onclick='say(\"message\");'>New</div>");
    document.getElementById("link").innerHTML = newstr;
    function say(message)
    {
      alert(message);
    }
  </script>
</body>
</html>
0
source

All Articles