从内容中删除特定标签并保留简码

时间:2018-09-19 01:27:13

标签: javascript html wordpress

如何从内容中删除所有HTML div标签并保留所有短代码。该脚本将删除所有div标签和短代码。

var html  = '<p>[my_shortcode post_id="2451"]';
    html += '<div class="parent-div-01"><div class="extras"><div>div lvl 3</div>line 01<br>line 01<br></div></div></p>';
    html += '<p>[my_shortcode post_id="1542"]';
    html += '<div class="parent-div-02"><div class="extras"><div>div lvl 3</div>line 01<br>line 01<br></div></div></p>';

function shortcode_constrict(html) {		
  return html.replace( /<div.*?<\/div>/g, "" );
}
console.log(shortcode_constrict(html));

1 个答案:

答案 0 :(得分:1)

使用DOM解析:

var html  = '<p>[my_shortcode post_id="2451"]';
    html += '<div class="my-div-01"><div class="my-div-01">Content div 01</div></div></p>';
    html += '<p>[my_shortcode post_id="1542"]';
    html += '<div class="my-div-02"><div class="my-div-02">Content div 01</div></div></p>';

function shortcode_constrict(html) {
  // Load the HTML string as XML, wrap it in a <root> tag as a XML doc needs one
  var doc = new DOMParser().parseFromString('<root>' + html + '</root>', 'text/xml');
  
  // Remove all div elements
  doc.querySelectorAll('div').forEach(function(div) {
    div.parentNode.removeChild(div);
  });
  
  // Return the modified document's HTML content
  return doc.documentElement.innerHTML;
}

console.log(shortcode_constrict(html));