给定一个 html 字符串,在 javascript 中仅删除锚 HTML 标记的最佳方法是什么?
Let's say there's a string of HTML, with script tags, plain text, whatever.
What's the best way to strip out only the <a>
tags?
I've been using some methods here, but these are for all tags. Strip HTML from Text JavaScript
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 jQuery:
添加一个包装
标签使我们能够获取所需的 HTML。
我在博客上写了更详细的解释 。
Using jQuery:
Adding a wrapping
<div>
tag allows us to get the desired HTML back.I wrote a more detailed explanation on my blog.
这种方法将保留现有的 DOM 节点,如果锚点内的元素附加了事件,则可以最大限度地减少副作用。
使用(使用 jQuery):
使用(不使用 jQuery):
This approach will preserve existing DOM nodes, minimizing side-effects if you have elements within the anchors that have events attached to them.
To use (with jQuery):
To use (without jQuery):
A标签不应包含任何其他 。标签,所以一个简单的不贪婪的正则表达式就可以解决这个问题(即
string.match(/
(.*?)<\/a>/)
,但这个例子假设标签有无属性)。A <a> tag is not supposed to hold any other <a> tag, so a simple ungreedy regexp would do the trick (i.e.
string.match(/<a>(.*?)<\/a>/)
, but this example suppose the tags have no attribute).如果性能是一个问题,这里有一个本机(非库)解决方案。
像这样使用它:
Here's a native (non-library) solution if performance is a concern.
Use it like this: