如何使用javascript将文本链接转换为客户端的HTML链接

xRo*_*bot 0 html javascript css database jquery

在我的数据库中,我保存了表单中的每个链接:

www.example.com or http://www.example.com
Run Code Online (Sandbox Code Playgroud)

有没有办法将这个文本链接转换为客户端的HTML链接(例如javascript),标签和参数如下?:

<a href="http://www.example.com" rel="nofollow">www.example.com</a>
Run Code Online (Sandbox Code Playgroud)

jev*_*lio 5

像cherouvim建议的那样在服务器端这可能会更聪明,但是这是一个(天真的)javascript函数,它为指定的格式(带和不带http:// - 前缀的 url )执行此操作

    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>';
    }
Run Code Online (Sandbox Code Playgroud)

请注意它不能很好地处理意外输入(https ...),所以请不要在生产环境中使用原样:)