function stripTags(string, tag) {
var tagMatcher = new RegExp('</?' + tag + '>','g');
return string.replace(tagMatcher, '');
}
to remove any tag from a string or
function toggleSurroundingTags(string, tag) {
var tagMatcher = new RegExp('^<' + tag + '>(.*)</' + tag + '>$');
var match = tagMatcher.exec(string);
if (match) {
return match[1];
} else {
return '<' + tag + '>' + string + '</' + tag + '>';
}
}
To remove surrounding tags if they exist and add them if they do not exist:
toggleSurroundingTags('hello', 'b'); // returns '<b>hello</b>'
toggleSurroundingTags('<b>hello</b>', 'b'); // returns 'hello'
source
share