7

I had made one div tag and stored its contents in a variable. If this tag contains p,b or any other tags then it should be removed from string. How can I achieve this?

2
  • add a jsfiddle to show us some code Commented Mar 14, 2014 at 7:26
  • Possible duplicate of Strip HTML from Text JavaScript Commented Nov 12, 2015 at 8:07

6 Answers 6

18

use the regular expression.

var regex = /(<([^>]+)>)/ig
var body = "<p>test</p>"
var result = body.replace(regex, "");

alert(result);

HERE IS THE DEMO

Hope this helps.

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

3 Comments

This solution breaks for this valid string: "<img alt=\"a>b\" src=\"a_b.gif\" />"
Check bellow stackoverflow.com/a/43087700/2012407 for additional info and larger coverage.
The solution is perfect
8

You can follow this example

var stringContent = "<p>Hi dear</p><p>Wish you a happy birthday</p>";

var text = $(stringContent).text();

Comments

5

This is safer:

function plaintext(html){
  return $("<div/>").html(html).text();
}

Comments

4

I would like to add a few things on top of the accepted answer which is suggesting the regex var regex = /(<([^>]+)>)/ig:


Final code:

var regex = /<\/?\w+[^>]*\/?>/g,
    body = "<sTrong><b>test<b></STRONG><b> sss</b><em> what if you write some maths: i < 2 && i > 4.</em>";

alert(body.replace(regex, ""));

It can also be helpful to place the function in the built-in 'String' class so you can do this directly :

"<em>test</em>".stripTags()

String.prototype.stripTags = function()
{
    return this.replace(/<\/?\w+[^>]*\/?>/g, '');
};

Eventually, if your string is a DOM node, you can do alert(element.innerText || element.textContent); which is built-in and even safer! See example here: http://jsfiddle.net/66L6nfwt/6/

Comments

1

Using plain javascript you can do it as

string.replace(/(<([^>]+)>)/ig,"");

I think this is probably faster than the .text() method.

Comments

0

Solution Using JQuery:

var content = "<p>Dear Andy,</p><p>This is a test message.</p>";

var text = $(content).text();

Solution using JavaScript:

function removeTags(){
    var txt = document.getElementById('myString').value;
    var rex = /(<([^>]+)>)/ig;
    alert(txt.replace(rex , ""));

}

Also look a this link: Strip HTML Tags in JavaScript

Comments

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.