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?
-
add a jsfiddle to show us some codeAbhidev– Abhidev2014-03-14 07:26:50 +00:00Commented Mar 14, 2014 at 7:26
-
Possible duplicate of Strip HTML from Text JavaScriptnhahtdh– nhahtdh2015-11-12 08:07:41 +00:00Commented Nov 12, 2015 at 8:07
6 Answers
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.
3 Comments
I would like to add a few things on top of the accepted answer which is suggesting the regex
var regex = /(<([^>]+)>)/ig:
- you don't need the
iflag in your regex as you don't match any alphabetic character. See here: http://jsfiddle.net/66L6nfwt/2/ - you don't need any pair of brackets as you just replace with nothing the whole match. See here: http://jsfiddle.net/66L6nfwt/3/
- This regex can be improved as it will fail if you use both chars
<and>in your text content. See here: http://jsfiddle.net/66L6nfwt/4/ - So here is a regex improvement:
/<\/?\w+[^>]*\/?>/g. See here: http://jsfiddle.net/66L6nfwt/5/
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
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