当用户在我的论坛中发布链接时,我将用该链接内容的预览替换它(类似于Facebook新闻源)。但是,我只想替换链接,如果它出现在段落的末尾(或者如果它是段落中的唯一元素)。
例如:
我做想要在这种情况下替换链接:
<p>Check out this cool website:
<a href="http://google.com">http://google.com</a></p>
但在这种情况下我不想要替换它:
<p>Check out this cool website:
<a href="http://google.com">http://google.com</a> – isn't it great?</p>
要实现这一点,我需要区分其后有文本的链接和不具有文本的链接。我的第一个想法是测试$the_link_in_question.is(":last-child")
,但后来我意识到:last-child
忽略了文本节点。
我想我可以做类似的事情:
$the_link_in_question.parent().contents().last()[0] == $the_link_in_question[0]
但这种方法让我呕吐在我的嘴里。想法?
答案 0 :(得分:2)
您只需检查.html()
,看看它是否以</a>
:
if (/<\/a>$/i.test($p.html())) {
var previewMe = $p.children().last();
}
如果您的锚点可能被包裹在其他元素中,例如,您需要更复杂的正则表达式。 <strong>
(您的原始方法也无法处理这些案例):
<p>content <strong><a href="...">link</a></strong></p>
在这种情况下,您可以使用此正则表达式:
/<\/a>(<\/.+?>)*$/