0

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.

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

Thank you for the heads up. I was just using this as a example of how we could search and replace unwanted html in our javascript code using regex (assuming the text-editor/IDE we are using supports regex search and replace).
True, but html is a cascading language, and a regular expression is actually not the right too to edit cascading languages, in that case you need to use context-free grammars, or xpath-like approaches. This can indeed work for small html source files, but will fail from the moment some tags are placed between tags to be deleted.
Point taken. Thanks once again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.