如何使用javascript/jquery查找和替换html字符串中的开始标记和结束标记
如何使用javascript/jquery查找和替换html字符串中的开始标记和结束标记 比如说如何使用javascript/jquery查找和替换html字符串中的开始标记和结束标记,javascript,jquery,Javascript,Jquery,如何使用javascript/jquery查找和替换html字符串中的开始标记和结束标记 比如说 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
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>";
var myString=“你好,约翰喜欢弹吉他,安娜喜欢插花
";
我需要找到“div”标记并替换为其他html标记,如“p”标记/“span”标记
将“div”标记替换为“p”标记后生成的html字符串
约翰喜欢弹吉他;font-weight:bold“class='classquotes'>安娜喜欢插花
”;
请建议任何解决方案。myString=$('').html(myString.find('div')。replaceWith(function()){
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();
var p=$(“”);
p、 html($(this.html());
$.each(this.attributes,function(index,attr){
p、 属性(attr.name,attr.value);
});
返回p;
}).end().html();
.带正则表达式的Javascript:
myString = myString.replace(/<(\/)?div[^>]*>/g, '<$1p>');
myString=myString.replace(/]*>/g',);
也看我的
==更新===
myString = myString.replace(/<(\/)?div([^>]*)>/g, '<$1p$2>');
myString=myString.replace(/]*)>/g',);
.但是,我不确定它是否比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();
}
);
正则表达式方法很好,但是如果我们使用它,标记的属性就会丢失。我们需要在使用时保留所有属性和样式。因此,它需要修改。如果需要用特定的类名替换div标记,如何修改第二个fiddle?
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();
}
);