How to find and replace start and end tags in an html string using javascript / jquery

How to find and replace start and end tags in an html string using javascript / jquery

eg

var myString = "<span> Hello john</span><div> John likes to play guitar </div> <div style="color:Blue;font-weight:bold" class='quotes'>Anna likes to arrange flowers </div>"; 

I need to find the "div" tag and replace it with another html tag, like the "p" tag / "span" tag

The resulting html line after replacing the div tag with the p tag

 var replacestring="<span> Hello john</span><p> John likes to play guitar </p> <p style="color:Blue;font-weight:bold" class='quotes'>Anna likes to arrange flowers </p>"; 

Please suggest any solution.

+7
source share
3 answers

Javascript with regex:

 myString = myString.replace(/<(\/)?div[^>]*>/g, '<$1p>'); 

Also see my jsfiddle .

=== UPDATE ===

 myString = myString.replace(/<(\/)?div([^>]*)>/g, '<$1p$2>'); 

jsfiddle 2 .

+2
source
 myString = $('<div />').html(myString).find('div').replaceWith(function() { var p = $('<p />'); p.html($(this).html()); $.each(this.attributes, function(index, attr) { p.attr(attr.name, attr.value); }); return p; }).end().html(); 

jsFiddle .

+4
source
However, I'm not sure if this is better than what alex suggested.
 var $replaceString=$(replaceString); $("div",$replaceString).each( function() { var $p=$(document.createElement('p')).html($(this).html()); //add code to add any attribute that you want to be copied over. $(this).after($p); $(this).remove(); } ); 
0
source

All Articles