[英]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 如何使用javascript / jquery在html字符串中查找和替换begin标签和结束标签
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 我需要找到“div”标签并替换为其他html标签,如“p”标签/“span”标签
Resulting html string after replace "div" tag to "p" tag 将“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>";
Please suggest any solution. 请建议任何解决方案。
Javascript with regular expression: 正则表达式的Javascript:
myString = myString.replace(/<(\/)?div[^>]*>/g, '<$1p>');
Also see my jsfiddle . 另见我的jsfiddle 。
=== UPDATE === ===更新===
myString = myString.replace(/<(\/)?div([^>]*)>/g, '<$1p$2>');
jsfiddle 2 . jsfiddle 2 。
Trying something with jQuery, however, I am not sure if it is any better than what alex suggested. 然而,尝试使用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.