编辑: 我有一个在标签之间包装字符串的函数。我希望仅当字符串不包含任何标签时才应用此函数。
if string: "text" then "<b>text</b>";
else if string "<b>text</b>" then "text";
我需要一个条件语句来检查给定的标签并仅在找到标签时去除标签。
例如。 函数 stripTags(string, "span")
1- 搜索给定标签(在本例中为 span)
2- 如果找到,剥离标签
最佳答案
function stripTags(string, tag) {
var tagMatcher = new RegExp('</?' + tag + '>','g');
return string.replace(tagMatcher, '');
}
从字符串中删除任何标签或
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 + '>';
}
}
删除周围的标签,如果它们存在,如果它们不存在,添加它们:
toggleSurroundingTags('hello', 'b'); // returns '<b>hello</b>'
toggleSurroundingTags('<b>hello</b>', 'b'); // returns 'hello'
关于Javascript:仅当找到标签时才剥离标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4478076/