views:

102

answers:

2

In my db I have saved every links in the form:

www.example.com or http://www.example.com

Is there a way to turn this text links into HTML links at the client side ( e.g. javascript ) with tag and parameter like this ?:

<a href="http://www.example.com" rel="nofollow">www.example.com</a>
+5  A: 

This would probably be smarter to do on the server side like cherouvim suggested, but here's a (naive) javascript function that does this for the specified formats (url with and without http://-prefix)

    function makeLink(link) { 
        var url, desc;

        if (link.match('^http://')) {
            url = link;
            desc = link.substr(7, link.length - 7);
        } else {
            url = 'http://' + link;
            desc = link;
        }

        return '<a href="' + url + '" rel="nofollow">' + desc + '</a>';
    }

Please note it doesn't handle unexpected input (https...) very well, so please don't use as-is in production environment :)

fencliff
Do you really think `rel=nofollow` is of any use, since this is generated on the client?
nikc
@nikc - I was just fulfilling the OP's request. Point taken though.
fencliff
Oops! Didn't see that up there. Sorry. :-)
nikc
A: 

I would try it like this:

text.replace(/([A-Za-z]+:\/\/)?[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(url) {
return url.link(url);
})
FB55
I'm tempted to downvote. This is like answering 42 to the question "What is the answer to life, the universe and everything." It may well be true, but doesn't really explain anything.
nikc