Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace particular html tags using javascript

Tags:

javascript

I want to replace every <li> tag with # & every </li> with <br />

I think I need a global replace function for that rather than a simple string.replace() so...

var s=obj1.innerHTML;

 s = s.replace(/<li>/g,&quot;# &quot;);
 s = s.replace(/</li>/g,&quot;<br/>&quot;);

But it doesn't seem to be working. Any mistake ?

EDIT: I am going to use the code in blogger & that is why it needs to be parsed.So that's why you see &quot; instead of ".

like image 689
Sangram Nandkhile Avatar asked May 30 '12 12:05

Sangram Nandkhile


2 Answers

Do this way:-

LIVE DEMO

var s="<div>hello world <br/><li>First LI</li><li>Second LI</li></div>";   
s = s.replace(/<li>/g, "#");  
s = s.replace(/<\/li>/g,"<br/>"); 
alert(s);
like image 136
Siva Charan Avatar answered Sep 19 '22 16:09

Siva Charan


obj1.innerHTML = obj1.innerHTML.replace(/<li>/g, '#').replace(/<\/li>/g, '<br>');

You just have to escape the / in /li otherwise it will be taken as a regex delimiter.

like image 41
ziad-saab Avatar answered Sep 18 '22 16:09

ziad-saab