EDIT: I have a function that wraps a string between tags. I want this function to apply only if the string does not contain any tags.
if string: "text" then "<b>text</b>";
else if string "<b>text</b>" then "text";
I need a conditional statement that checks for given tags and strips the tags only if tags are found.
eg. function stripTags(string, "span")
1- search for given tags (span in this case)
2- if found, strip tags
function stripTags(string, tag) {
var tagMatcher = new RegExp('</?' + tag + '>','g');
return string.replace(tagMatcher, '');
}
to remove any tag from the 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 don't exist:
toggleSurroundingTags('hello', 'b'); // returns '<b>hello</b>'
toggleSurroundingTags('<b>hello</b>', 'b'); // returns 'hello'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With