Grow your CSS skills. Land your dream job.

JQuery – Detect if Text URL Wrapped by Anchor Tag

  • # March 13, 2012 at 3:02 am

    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.

    # March 13, 2012 at 10:41 am

    Hey Hompimpa,
    Not exactly sure what you’re trying to so here?
    is it change the target of the existing anchor on the page?

    # March 13, 2012 at 9:52 pm

    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!

    http://www.google.com">
    http://www.google.com

    I’ve tried this:

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

    so the element that not useful will be removed. But I think this way is not quite cute.

    # March 14, 2012 at 9:41 am

    I got it!
    So, instead of replacing the matched string into a link, it would be better if we turn it into a element first. Then, when all the matched strings has been wrapped by , 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 ``
    $('body').html($('body').html().replace(exp, "$1"));

    $('.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('' + $(this).text() + '');
    });

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

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".