2013-04-16 50 views
0

我发现这个JS上,这样看起来会检测包括经常链接和Twitter和#哈希标签工作@使用者名称这里很大脚本:的Javascript正则表达式中删除HTTP://和https://从文本

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.也会很好。但实际上,我只需要知道如何通过可能有多个链接/提及/标签的推文重复此操作。谢谢!

回答

3

试试这个:

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); 
    } 
+0

刚才试了,它工作正常...'processTweetLinks('HTTP ://google.com')'产生'google.com' –

+0

是的,它是完美的!只要我的新手眼睛可以看到它没有错!谢谢@BrunoFinelli!我所做的唯一小小的监督就是'www.',那么也可以很好地将其删除? – tylerl

+0

我没有意识到它只在每次运行时才被应用到一个链接......您能否修改您的答案,以便它可以修复给定字符串中的多个链接?谢谢! – tylerl

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>"); 
相关问题