例如,如何将纯 URL 替换为链接

How to replace plain URLs with links, with example?

本文关键字:URL 替换 链接 例如      更新时间:2023-09-26

我几乎可以正常工作了。 我想知道是否有更好的方法。

根本问题

小提琴

function replaceURLWithHTMLLinks(text) {
    text = text.replace(/a/g, "--ucsps--");
    text = text.replace(/b/g, "--uspds--");
    var arrRegex = [
        /('([^)]*'b)((?:https?|ftp|file):'/'/[-A-Za-z0-9+&@#'/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#'/%=~_()|])('))/ig,
        /('([^)]*'b)((?:https?|ftp|file):'/'/[-A-Za-z0-9+&@#'/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#'/%=~_()|])(.?'b)/ig,
        /()('b(?:https?|ftp|file):'/'/[-a-z0-9+&@#'/%?=~_()|!:,.;]*[-a-z0-9+&@#'/%=~_()|])(.?'b)/ig];
    for (i = 0; i < arrRegex.length; i++) {
        text = text.replace(arrRegex[i], "$1a$2b$3");
    }
    text = text.replace(/a([^b]*)b/g, "<a href='$1'>$1</a>");
    text = text.replace(/--ucsps--/g, "a");
    text = text.replace(/--uspds--/g, "b");
    return text;
}
var elm = document.getElementById('trythis');
elm.innerHTML = replaceURLWithHTMLLinks(elm.innerHTML);

有什么想法吗?

在CodeReview上,这个问题得到了很好的回答。

function replaceURLWithHTMLLinks(text) {
    var re = /('(.*?)?'b((?:https?|ftp|file):'/'/[-a-z0-9+&@#'/%?=~_()|!:,.;]*[-a-z0-9+&@#'/%=~_()|])/ig;
    return text.replace(re, function(match, lParens, url) {
        var rParens = '';
        lParens = lParens || '';
        // Try to strip the same number of right parens from url
        // as there are left parens.  Here, lParenCounter must be
        // a RegExp object.  You cannot use a literal
        //     while (/'(/g.exec(lParens)) { ... }
        // because an object is needed to store the lastIndex state.
        var lParenCounter = /'(/g;
        while (lParenCounter.exec(lParens)) {
            var m;
            // We want m[1] to be greedy, unless a period precedes the
            // right parenthesis.  These tests cannot be simplified as
            //     /(.*)('.?').*)/.exec(url)
            // because if (.*) is greedy then '.? never gets a chance.
            if (m = /(.*)('.').*)/.exec(url) ||
                    /(.*)(').*)/.exec(url)) {
                url = m[1];
                rParens = m[2] + rParens;
            }
        }
        return lParens + "<a href='" + url + "'>" + url + "</a>" + rParens;
    });
}

注意:我在"var re"中的"@"符号有错误 - 我只是用@@替换了它

猜这个问题已经在这里回答了

function replaceURLWithHTMLLinks(text) {
    var exp = /('b(https?|ftp|file):'/'/[-A-Z0-9+&@#'/%?=~_|!:,.;]*[-A-Z0-9+&@#'/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}