Is it possible to detect if there is a text URL that has been wrapped by the anchor tag, so I can manage the target of this snippet. I've tried Googling but nothing.
I got it! So, instead of replacing the matched string into a link, it would be better if we turn it into a <span> element first. Then, when all the matched strings has been wrapped by <span>, remove all the original link that might wrap this element. And the last, just replace the span with an anchor tag. It works! YAY!
// Detect links pattern var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
// Wrap the matched strings with `<span class="fake-link"></span>` $('body').html($('body').html().replace(exp, "<span class='fake-link'>$1</span>"));
$('.fake-link').each(function() { // Extra job: Check if parent is an anchor if ($(this).parent().is('a')) { // If `true`, then unwrap the original anchor which has been written by default from `.fake-link` $(this).unwrap(); } // Replace `.fake-link` with an anchor tag $(this).replaceWith('<a href="' + $(this).text() + '">' + $(this).text() + '</a>'); });
Here is my Fiddle: http://jsfiddle.net/tovic/q9eVb/
Thank you very much.
Not exactly sure what you're trying to so here?
is it change the target of the existing anchor on the page?
I've tried this:
so the
<a>element that not useful will be removed. But I think this way is not quite cute.So, instead of replacing the matched string into a link, it would be better if we turn it into a
<span>element first. Then, when all the matched strings has been wrapped by<span>, remove all the original link that might wrap this element.And the last, just replace the
spanwith an anchor tag.It works! YAY!
http://jsfiddle.net/tovic/UQJT7/32/