且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将纯文本链接转换为可点击链接

更新时间:2023-02-23 09:25:09

看起来你替换的语法是错误的.

It looks like you're replace syntax is wrong.

试试这样的方法,我很确定这会奏效.

Try something like this, I'm pretty sure this will work.

function linkify(inputText) {
    var replacedText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /((https?|ftp)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^/])(www.[S]+(|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links.
    replacePattern3 = /(([a-zA-Z0-9-\_.])+@[a-zA-Z\_]+?(.[a-zA-Z]{2,6})+)/gim;
    replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText;
}

调用方式:


Calling it with:

$w('#text95').innerHTML = linkify($w('#text95').html);