我有一个包含HTML文档的长字符串。我想删除所有href标记,但保留文本。以下示例:
Some text <a href="mailto:mail@example.com">example 1</a></p> some <a href="www.example2.com"> example 2</a>text
应该变成:
Some text example 1 </p> some example 2 text
我找到的解决方案是获取所有文本,然后尝试再次遍历文本,并将标签号n替换为文本号n。
var a_string = 'Some text <a href="mailto:mail@example.com">example 1</a></p> some <a href="www.example2.com"> example 2</a>text',
el = document.createElement('p');
el.innerHTML = a_string;
var a = el.querySelectorAll('a');
var texts = [].slice.call(a).map(function(val){
return val.innerHTML;
});
alert(texts);
// TODO ieterate and replace occurence n with texts[n]
有什么更好的方法吗?
在第一行之后写入以下代码
a_string = a_string.replace(/(<a.*?>)/g,'').replace(/</a>/g,' ');
您可以使用以下Regex:
var regex = /(<s*a([^>]+)>|</s*as*>)/ig;
var str = 'Some text <a href="mailto:mail@example.com">example 1</a></p> some <a href="www.example2.com"> example 2</a>text';
str.replace(regex, ""); //Some text example 1</p> some example 2text
尝试以下正则表达式:
var a_txt = a_string.replace(/<a[s]+[^>]*?href[s]?=[s"']*(.*?)["']*.*?>/g,"").replace(/</a>/g," ");
查询选择所有a标记的解决方案实际上并不太糟糕。您可以迭代列表并用其内容替换每个元素,而不是用map获取文本。不需要正则表达式:
el.querySelectorAll('a').forEach(function( a_el ){
var text = document.createTextNode(a_el.innerText);
a_el.parentNode.replaceChild(text, a_el);
});
此外,您可以使用DomParser:
var parser = new DOMParser();
var doc = parser.parseFromString(a_string, "text/html");
doc.querySelectorAll('a').forEach(function( a_el ){
var text = document.createTextNode(a_el.innerText);
a_el.parentNode.replaceChild(text, a_el);
});
正如上面的一些答案所述,您的代码还不错。我在不必要的时候避免使用正则表达式。为了完成代码,您需要遍历所有的A{ELEMENTS}。我在用手机打字。如果您遇到错误,请告诉我。谢谢
var a_string = 'Some text <a href="mailto:mail@example.com">example 1</a></p> some <a href="www.example2.com"> example 2</a>text',
el = document.createElement('p');
el.innerHTML = a_string;
var a = el.querySelectorAll('a');
for( var t = a.length - 1; t >=0 ; t-- ){
for(var c = a[t].childNodes.length - 1; c >= 0; c-- ){
if( a[t].nextSibling ){
document.insertBefore( a[t].childNodes[c], a[t].nextSibling );
} else {
a[t].parentNode.appendChild( a[t].childNodes[c]);
}
}
a[t].remove();
}