简体   繁体   English

使用javascript替换开始和结束的多个html标签

[英]Replace starting and ending multiple html tags using javascript

I want to remove following tags 我想删除以下标签

  1.  <div>
  2.  </div>
  3.  <p>
  4.   </p>
  5.   <span>
  6.   </span>

var str =  '<div><p><span>Hello World</span></p></div>';

I can do 我可以

str = str.replace('<div>', '');
str = str.replace('<p>', '');

and so on. 等等。

But using regular expressions etc can we accomplish the same in 1 step. 但是使用正则表达式等可以一步完成相同的任务。

Do not use regexes for this: RegEx match open tags except XHTML self-contained tags 请勿为此使用正则表达式: RegEx匹配除XHTML自包含标记之外的其他开放标记

Parse the HTML and retrieve what you need. 解析HTML并检索您需要的内容。 This is a basic one, that retrieves the text from the nodes you supplied. 这是一种基本的方法,可以从您提供的节点中检索文本。 You can extend this further to seed your needs. 您可以进一步扩展它以播种您的需求。

 var container = document.createElement("div"); //load div in memory
 container.insertAdjacentHTML("afterbegin", str); //append the nodes into the container div.

 str = container.getElementsByTagName("span")[0].textContent || container.getElementsByTagName;("span")[0].innerText;

You can even do container.textContent || container.innerText 您甚至可以做container.textContent || container.innerText container.textContent || container.innerText ; container.textContent || container.innerText ; to get all text and no nodes from the string container HTML elements. 从字符串容器HTML元素中获取所有文本且没有节点。 (innerText is there to support older browsers, IE). (innerText在那里支持较旧的浏览器IE)。

Try this pattern: 试试这个模式:

/<\/?([a-z])+\>/g

Heres an example 这是一个例子

RegExr v2.0 is a very handy tool for testing regular expression. RegExr v2.0是用于测试正则表达式的非常方便的工具。 In order to see the result, click on the "substitution" tab on the bottom of the page. 为了查看结果,请单击页面底部的“替换”选项卡。

Hope this is what you were looking for. 希望这就是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM