18

I'm trying to replace html using innerHTML javascript.

From:

aaaaaa/cat/bbbbbb

To:

<a href="http://www.google.com/cat/world">Helloworld</a>

This's my code

<html>
<head>
</head>
<body>
<p id="element1">aaaaaa/cat/bbbbbb</p>

<script language="javascript">
var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML.replace( /aaaaaa./g,'<a href=\"http://www.google.com/') ;
strMessage1.innerHTML = strMessage1.innerHTML.replace( /.bbbbbb/g,'/world\">Helloworld</a>') ;
</script>
</body>
</html>

When i run this code it disappears Helloworld hyperlink. what I'm doing wrong. Please help.

Thank you for all your help.

Dexter
  • 183
  • 1
  • 1
  • 4

2 Answers2

28

You should chain the replace() together instead of assigning the result and replacing again.

var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
                        .replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
                        .replace(/.bbbbbb/g,'/world\">Helloworld</a>');

See DEMO.

Antony
  • 14,900
  • 10
  • 46
  • 74
  • I did this, but it breaks the rest of the page from wherever it's inserted. – M21 Nov 14 '18 at 19:10
  • @M21 HTML string replace is more like a fun exercise than a reliable solution. If you have a slightly different problem, please ask your own question. Illustrate with an example of why it doesn't work in your question, show us what you have tried, and you can also link to this question if you want. – Antony Nov 15 '18 at 03:06
5

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    This works as well for me, but breaks the rest of the page from wherever it's put. – M21 Nov 14 '18 at 19:11