Javascript - Replace html with innerHTML

I am trying to replace html with innerHTML javascript.

From:

aaaaaa/cat/bbbbbb 

To:

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

This is 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 hides the Helloworld hyperlink. what am I doing wrong. Please, help.

Thank you for your help.

+6
source share
2 answers

You should combine 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 .

+11
source

You replace the start tag and then put it back in innerHTML , so the code will be invalid. Make all replacements before returning the code to 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; 
+2
source

All Articles