Javascript - Replace html using innerHTML
Asked Answered
F

2

19

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.

Farrier answered 25/3, 2013 at 15:19 Comment(0)
B
30

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.

Befog answered 25/3, 2013 at 15:24 Comment(2)
I did this, but it breaks the rest of the page from wherever it's inserted.Edik
@Edik 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.Befog
M
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;
Mooch answered 25/3, 2013 at 15:22 Comment(1)
This works as well for me, but breaks the rest of the page from wherever it's put.Edik

© 2022 - 2024 — McMap. All rights reserved.