Alex Rivera | Logout

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

Asked 2011-10-10T05:53:45.873
8

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

for example

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 with other html tag like "p" tag/ "span" tag

Resulting html string after replace "div" tag to "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.

Edit
Report

1 Answer

0

Trying something with jQuery, however, I am not sure if it is any 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();
    }
);
answered 2011-10-10T06:20:39.500

Your Answer