我有以下字符串变量,想要替换所有html标签和格式,但希望保留锚标记而不进行格式化,以便保持可点击状态。
content = "<div><a href=\"1\">I</a> was going here and then <a href=\"that\">that</a> happened.<p>Some Text here</p></div>";
应该看起来像
content = "<a href=\"1\">I</a> was going here and then <a href=\"that\">that</a> happened. Some Text here"
答案 0 :(得分:0)
试试这个,
content = "<div><a href=\"1\">I</a> was going here and then <a href=\"that\">that</a> happened.<p>Some Text here</p></div>";
var output = content.replace(/(<\/?(?:a)[^>]*>)|<[^>]+>/ig, '$1');
console.log(output);
&#13;
答案 1 :(得分:0)
不建议使用RegEx来解析HTML
我们可以考虑展开 - 这里有一个没有任何内部的P
如果P内部存在某些内容,我们需要循环每个标记
const content = "<div><a href=\"1\">I</a> was going here and then <a href=\"that\">that</a> happened.<p>Some Text here</p></div>";
let $html = angular.element(content);
console.log($html.html());
const $p = $html.find("p");
$p.replaceWith($p.text());
console.log($html.html());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
除了A之外的任何标记 - 仍然没有处理其他标记中包含的标记 - 为此我们需要递归循环:
How do I select the innermost element?
const content = "<div><a href=\"1\">I</a> was going here and then <a href=\"that\">that</a> happened.<p>Some Text here</p>. Here is a <span>span element1</span> some text <span>span element2</span></div>";
let $html = angular.element(content);
console.log($html.html());
const tags = $html.find("*");
for (let i=0;i<tags.length;i++) {
const $tag = angular.element(tags[i]);
const tagName = $tag[0].tagName;
if (tagName==="A") continue; // ignore A
$html.find(tagName).eq(0).replaceWith($tag.text()); // one at a time
};
console.log($html.html());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
答案 2 :(得分:0)
我使用以下方法删除除锚标记之外的所有标记。
value = value.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
let html = '', addToMax = false, extraLimit = 0;
if(value && typeof value === 'string' && value.length) {
let inDelete = false;
for(let i = 0; i < value.length; i++) {
if(value.charAt(i) == '<' && value.charAt(i + 1) && value.charAt(i + 1) != 'a') {
inDelete = true;
if(value.charAt(i + 1) == '/' && ((value.charAt(i + 2) && value.charAt(i + 2) == 'a') || (value.charAt(i + 2) == ' ') && value.charAt(i + 3) && value.charAt(i + 3) == 'a')) {
inDelete = false;
}
}
if(!inDelete) {
html += value.charAt(i);
}
if(inDelete && value.charAt(i) == '>') {
inDelete = false;
}
}
}
value = angular.copy(html);