Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 936
amexn Avatar asked Oct 10 '11 05:10

amexn


People also ask

How do I change text between tags?

str = str. replace(/<title>[\s\S]*? <\/title>/, '<title>' + newTitle + '<\/title>'); That should find and replace it.

How to replace DOM element jQuery?

To replace a DOM element with the specified HTML or DOM elements using jQuery, use the replaceWith() method. The replaceWith (content) method replaces all matched elements with the specified HTML or DOM elements. This returns the JQuery element that was just replaced, which has been removed from the DOM.


2 Answers

Javascript with regular expression:

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

Also see my jsfiddle.

=== UPDATE ===

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

jsfiddle 2.

like image 113
scessor Avatar answered Sep 28 '22 09:09

scessor


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.

like image 32
alex Avatar answered Sep 28 '22 10:09

alex