When a user posts a link in my forum, I’m going to replace it with a preview of that linked content (something like the Facebook news feed). However, I only want to replace the link if it appears at the end of a paragraph (or if it’s the only element in a paragraph).
For example:
I do want to replace the link in this case:
<p>Check out this cool website:
<a href="http://google.com">http://google.com</a></p>
but I don’t want to replace it in this case:
<p>Check out this cool website:
<a href="http://google.com">http://google.com</a> – isn't it great?</p>
To accomplish this, I need to differentiate between links that have text after them and links that don’t. My first thought was to test $the_link_in_question.is(":last-child"), but then I realized that :last-child ignores text nodes.
I suppose I could do something like:
$the_link_in_question.parent().contents().last()[0] == $the_link_in_question[0]
But this approach makes me throw up in my mouth. Thoughts?
You can simply check the
.html()to see if it ends in</a>:You’ll need a more complicated regex if it’s possible that your anchors can get wrapped in other elements, e.g.
<strong>(your original approach couldn’t handle these cases either):In which case, you can use this regex: