Replace html tags with javascript

I want to replace each <li> with # and each </li> with <br />

I think I need the Global repalce function for this, and not just string.replace() , so ..

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

But it does not seem to work. Any mistake?

EDIT: I am going to use the code in a blogger, and therefore it needs to be parsed. Therefore you see &quot; instead of " .

+4
source share
4 answers

Do this: -

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); 
+14
source
 obj1.innerHTML = obj1.innerHTML.replace(/<li>/g, '#').replace(/<\/li>/g, '<br>'); 

You just need to avoid / in /li , otherwise it will be used as a regex separator.

+6
source

This works great:

 <html> <head> <script type="text/javascript" src="http://streamed.in/static/js/jquery-1.4.1.min.js"></script> <script> $(document).ready(function(){ var s = $('#obj1').html(); s = s.replace(/<li>/g,'#'); s = s.replace(/<\/li>/g,'<br/>'); $('#obj1').html(s); }); </script> </head> <body id="obj1"> <li>omg 1</li> <li>omg 2</li> <li>omg 3</li> <li>omg 4</li> </body> </html> 

or you can try replacing the second replacement string:

 s.replace(/<\/li>/g,'<br/>'); 
0
source

If you can use jQuery, this will help you:

$("li").after("#<br/>").remove();

-3
source

Source: https://habr.com/ru/post/1415153/


All Articles