簡體   English   中英

如何使用javascript / jquery在html字符串中查找和替換begin標簽和結束標簽

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

如何使用javascript / jquery在html字符串中查找和替換begin標簽和結束標簽

例如

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>";

我需要找到“div”標簽並替換為其他html標簽,如“p”標簽/“span”標簽

將“div”標記替換為“p”標記后生成的html字符串

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>";

請建議任何解決方案。

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

正則表達式的Javascript:

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

另見我的jsfiddle

===更新===

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

jsfiddle 2

然而,嘗試使用jQuery,我不確定它是否比alex建議的更好。

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();
    }
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM