Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: strip tags ONLY IF tags found

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

like image 847
Zebra Avatar asked Aug 13 '26 21:08

Zebra


1 Answers

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'
like image 172
Jan Avatar answered Aug 15 '26 11:08

Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!