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
I would like to add a few things on top of the accepted answer which is suggesting the regex
var regex = /(<([^>]+)>)/ig
:
i
flag in your regex as you don't match any alphabetic character. See here: http://jsfiddle.net/66L6nfwt/2/<
and >
in your text content. See here: http://jsfiddle.net/66L6nfwt/4//<\/?\w+[^>]*\/?>/g
. See here: http://jsfiddle.net/66L6nfwt/5/Final code:
var regex = /<\/?\w+[^>]*\/?>/g,
body = "test sss what if you write some maths: i < 2 && i > 4.";
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 :
"test".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/