2011-09-26 33 views
1

我之前在Flash中沒有寫過這樣的功能;不過,我現在試圖用JavaScript來做,而且我遇到了一些困難。REGEX Str替換 - 查找鏈接文本並將它們鏈接起來

使用正則表達式,我試圖沖刷一個字符串尋找類似鏈接的任何東西......例如http://www.google.comhttp://stacoverflow.com/question/ask;然後用適當的結果包裝該結果::

<script type="text/javascript> 
var mystring = "I'm trying to make this link http://facebook.com/lenfontes active." 
/// REGEX that worked in Flash to grab ALL parts of the URL including after the .com... 

var http = /\b(([\w-]+:\/\/?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/)))/gi; 

// preform the replace based on the Regex 
mystring = mystring.replace(http, function(){ 
    var link = arguments[0]; 
if (link.indexOf("http") == -1){ 
    link = "http://" + link;} 
    return "<a href='"+link+"'>"+arguments[0]+"</a>"; 
}); 

$('#results).html(mystring); 
</script> 

我遇到的問題:忽略com /後面的任何內容。因此,鏈接是不正確的...

即使我發佈這個問題,堆棧溢出接口採取了我的文本,並與相應的鏈接標記呈現出來......我需要這樣做。

歡迎任何建議。

- 更新:

對不起,讓我擴大..我不是隻想找的http://它需要檢測和包裝,與開始鏈接「https://開頭」和/或剛開始「WWW」

回答

2

你的正則表達式不起作用,因爲ECMA(JavaScript的)不支持POSIX字符類,所以[:punct:]忽略.com.