Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  95] [ 3]  / answers: 1 / hits: 164975  / 11 Years ago, mon, march 25, 2013, 12:00:00

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.


More From » innerhtml

 Answers
2

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.


[#79370] Sunday, March 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
micayla

Total Points: 148
Total Questions: 92
Total Answers: 109

Location: Aruba
Member since Sat, Oct 2, 2021
3 Years ago
micayla questions
Fri, Dec 24, 21, 00:00, 2 Years ago
Thu, Apr 16, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
;