Javascript:仅在找到标签时剥离标签

Zeb*_*bra 3 javascript jquery conditional-statements

编辑:我有一个函数,在标签之间包装一个字符串.我希望只有在字符串不包含任何标记时才应用此函数.

if string: "text" then "<b>text</b>";  
else if string "<b>text</b>" then "text";
Run Code Online (Sandbox Code Playgroud)



我需要一个条件语句来检查给定的标签,并仅在找到标签时剥离标签.

例如. function stripTags(string, "span")

1-搜索给定的标签(在这种情况下为span)
2 - 如果找到,剥离标签

Jan*_*Jan 6

function stripTags(string, tag) {
  var tagMatcher = new RegExp('</?' + tag + '>','g');
  return string.replace(tagMatcher, '');
}
Run Code Online (Sandbox Code Playgroud)

从字符串中删除任何标记或

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 + '>';
  }
}
Run Code Online (Sandbox Code Playgroud)

删除周围标记(如果存在)并添加它们(如果它们不存在):

toggleSurroundingTags('hello', 'b'); // returns '<b>hello</b>'
toggleSurroundingTags('<b>hello</b>', 'b'); // returns 'hello'
Run Code Online (Sandbox Code Playgroud)

  • 请记住,此代码不会考虑任何属性. (2认同)