I want to remove all the html tags except
or
tags from a string using javascript.
I have seen many questions like this but t
I've adapted Sandro Rosa's function to address the issue mentioned by Nikita:
function strip_tags( _html /*you can put each single tag per argument*/ )
{
var _tags = [], _tag = "";
for ( var _a = 1 ; _a < arguments.length ; _a++ ) {
_tag = arguments[_a].replace(/[<>\/]/g, '').trim();
if ( arguments[_a].length > 0 ) _tags.push( _tag );
}
if ( !( typeof _html == "string" ) && !( _html instanceof String ) ) return "";
else if ( _tags.length == 0 ) return _html.replace( /<\s*\/?[^>]+>/g, "" );
else
{
var _re = new RegExp( "<(?!\\s*\\/?(" + _tags.join("|") + ")\\s*\\/?>)[^>]*>", "g" );
return _html.replace( _re, '' );
}
}
var _html = "Just some tags and text to test this code" ;
console.log( "This is the original html code including some tags" );
console.log( _html ); // original html code
console.log( "Now we remove all tags (plain text)" );
console.log( strip_tags( _html ) ); // remove all tags
console.log( "Only the bold tag is kept" );
console.log( strip_tags( _html, "b" ) ); // keep only
console.log( "Only the underline tag is kept" );
console.log( strip_tags( _html, "u" ) ); // keep only
console.log( "Only the italic tag is kept" );
console.log( strip_tags( _html, "" ) ); // keep only
console.log( "Keeping both italic and underline" );
console.log( strip_tags( _html, "i", "u" ) ); // keep both and
_html = "this is my string and it's pretty cool
isn't it?
Yep, it is.More HTML tags" ;
console.log( "Keeping just the bold tag" );
console.log( strip_tags( _html, "b" ) ); // keep just the , not the
or