HTML字符串使用jQuery替换标记

时间:2018-02-16 11:36:22

标签: javascript jquery html

我有HTML字符串,其中包含各种元素。 请考虑以下是HTML字符串 -

var contentHTML = '<p>Some random string</p><p><img src="xyz.jpg" style="width: 100%;"><span some style></span></p><p><span style="font-size: 16.8px;"><b>Ingredients</b></span></p><p>Again some string</p><p><img src="xyz.jpg" style="width: 100%;"></p>';

我的要求是在每个img标记之前和之后获取标记。如果img标记之前的标记为p标记,则将其替换为<figure>并使用</p>结束</figure>

我尝试循环浏览img代码并能够完美地获取图像细节。

如何在图像之前和之后替换元素。

$(this.content).find('img').each(function() {
    console.log($(this).prev());
    console.log($(this).attr('src'));
});

我要求的字符串 -

var contentHTML = '<p>Some random string</p><figure><img src="xyz.jpg" style="width: 100%;"><span some style></span></figure><p><span style="font-size: 16.8px;"><b>Ingredients</b></span></p><p>Again some string</p><figure><img src="xyz.jpg" style="width: 100%;"></figure>';

2 个答案:

答案 0 :(得分:8)

使用replaceWith评论内联

var $contentHTML = $( "<div>" + contentHTML + "</div>");

$contentHTML.find( "img" ).each( function(){ //iterate all img elements
  var $parentP = $(this).parent(); //get the parent element
  if ( $parentP[0].nodeName == "P" ) //check if the parent Element is P
  {
     var innerHTML = $parentP.html(); //save the innerHTML value
     $parentP.replaceWith( "<figure>" + innerHTML + "</figure>" ); //replace with figure and retain saved html value
  }
});
console.log($contentHTML.html());

<强>演示

var contentHTML = `<p>Some random string</p><p><img src="xyz.jpg" style="width: 100%;"><span some style></span></p><p><span style="font-size: 16.8px;"><b>Ingredients</b></span></p><p>Again some string</p><p><img src="xyz.jpg" style="width: 100%;"></p>`;

var $contentHTML = $( "<div>" + contentHTML + "</div>");

$contentHTML.find( "img" ).each( function(){
  var $parentP = $(this).parent();
  if ( $parentP[0].nodeName == "P" )
  {
     var innerHTML = $parentP.html();
     $parentP.replaceWith( "<figure>" + innerHTML + "</figure>" );
  }
});
console.log($contentHTML.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

使用replaceregular expression

&#13;
&#13;
var contentHTML = '<p>Some random string</p><p><img src="xyz.jpg" style="width: 100%;"><span some style></span></p><p><span style="font-size: 16.8px;"><b>Ingredients</b></span></p><p>Again some string</p><p><img src="xyz.jpg" style="width: 100%;"></p>';
var result=contentHTML.replace(/<p([^>]*?)>\s*?<img([\s\S]*?)<\/p>/g,'<figure$1><img$2</figure>');
console.log(result);
&#13;
&#13;
&#13;