0

我在 SO 上找到了这个 JS 脚本,它似乎可以很好地检测常规链接和 Twitter #hashtags 和 @usernames:

function processTweetLinks(text) {
    text = text.replace();
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
    text = text.replace(exp, "<a href='$1' target='_blank'>$1</a>");
    exp = /(^|\s)#(\w+)/g;
    text = text.replace(exp, "$1<a href='http://search.twitter.com/search?q=%23$2' target='_blank'>#$2</a>");
    exp = /(^|\s)@(\w+)/g;
    text = text.replace(exp, "$1<a href='http://www.twitter.com/$2' target='_blank'>@$2</a>");
    console.log(text);
}

但是......第一个表达式不太适合我的需要......当它得到类似的东西时http://google.com,它会输出<a href='http://google.com' target='_blank'>http://google.com</a>。我希望它改为输出<a href='http://google.com' target='_blank'>google.com</a>- 基本上从锚标签内部删除http://或删除。https://我不知道正则表达式 - 函数需要是什么样子才能输出?

更新:我用@BrunoFinelli 的回答修复了这个函数,效果很好,但我不知道如何让它修复给定字符串/消息中的多个链接。现在,每次我调用该函数时它只修复一个......如果有人可以调整该函数来修复这个问题,那将不胜感激!谢谢!如果第一个正则表达式(有问题的那个)www.也从锚标签内部删除 's 也会很好吗?但实际上我只需要知道如何通过可能有多个链接/提及/标签的推文重复这一点。谢谢!

4

2 回答 2

3

Try this one:

    function processTweetLinks(text) {
        text = text.replace();
        var exp = /(\b(https?|ftp|file):\/\/)([-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
        text = text.replace(exp, "<a href='$1$3' target='_blank'>$3</a>");
        exp = /(^|\s)#(\w+)/g;
        text = text.replace(exp, "$1<a href='http://search.twitter.com/search?q=%23$2' target='_blank'>#$2</a>");
        exp = /(^|\s)@(\w+)/g;
        text = text.replace(exp, "$1<a href='http://www.twitter.com/$2' target='_blank'>@$2</a>");
        console.log(text);
    }
于 2013-04-16T21:06:25.633 回答
0

您需要在另一个捕获组中捕获 URL 的第二部分,并在锚标记中引用该组。

var exp = /(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]))/i;
text = text.replace(exp, "<a href='$1' target='_blank'>$3</a>");

您可以通过计算语句中出现左括号的时间来确定如何引用组。在上述情况下,您希望 href 等于整个语句(第一个左括号),并且您希望内部 html 匹配第三个左括号。

这也可以工作,因为$&插入了整个匹配的字符串:

var exp = /\b(https?|ftp|file):\/\/([-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
text = text.replace(exp, "<a href='$&' target='_blank'>$2</a>");
于 2013-04-16T21:02:05.113 回答