【问题标题】:Remove specific tags from content and keep shortcodes从内容中删除特定标签并保留简码
【发布时间】:2018-09-19 19:15:49
【问题描述】:

如何从内容中删除所有 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));

【问题讨论】:

  • 您可能想在您的正则表达式中将.* 替换为.*?(使量词惰性)。 &lt;p&gt;s 应该留在那里吗?另一方面,使用DOM parsing 可能会更干净,因为它看起来像一个 HTML 字符串。
  • @Jeto 我只想删除 div 标签。
  • @Jeto 抱歉,这仅适用于第一级 div,但不适用于另一个 div 内的 div。我修改了上面的脚本。
  • 见下面的答案。正如我在第一条评论中提到的那样,使用 DOM 解析应该更有效/更合适。

标签: javascript html wordpress


【解决方案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));

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 2018-10-06
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2015-12-13
    • 2022-01-01
    • 2017-04-06
    • 1970-01-01
    相关资源
    最近更新 更多