简体   繁体   中英

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

Parse the HTML and retrieve what you need. 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 ; to get all text and no nodes from the string container HTML elements. (innerText is there to support older browsers, IE).

Try this pattern:

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

Heres an example

RegExr v2.0 is a very handy tool for testing regular expression. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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