treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] JQuery - Detect if Text URL Wrapped by Anchor Tag

  • 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.

    Here is my Fiddle: http://jsfiddle.net/tovic/q9eVb/

    Thank you very much.
  • Hey Hompimpa,
    Not exactly sure what you're trying to so here?
    is it change the target of the existing anchor on the page?
  • This snippet is used to change the plain URL becomes active URL automagically. But when the real URL caught they are become a little CRAZY!

    <a href="<a href="http://www.google.com">http://www.google.com</a>"></a&gt;
    <a href="http://www.google.com">http://www.google.com</a&gt;


    I've tried this:

    $('body').find('a[href=^<]:empty').remove();


    so the <a> element that not useful will be removed. But I think this way is not quite cute.
  • 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>');
    });


    http://jsfiddle.net/tovic/UQJT7/32/