![](/img/trans.png)
[英]how to find string in html tag and replace using javascript/jquery
[英]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>');
然而,尝试使用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.