2013-04-10 36 views
0

我需要自動鏈接頁面中的URL。使用jquery自動鏈接頁面中的網址

例如

這是一個HTML內容和包含文本URL www.example.com和鏈接的URL < A HREF = 'www.example.com' >例如< /一個>。它可能後跟HTTP像[http://www.example.com]

我需要的結果是這樣的:

這是HTML內容,幷包含文字網址http://www.example.com和鏈接的URL http://www.example.com。它可能跟着像http://www.example.com

我已經使用下面的功能,但它不與URL開始與www。

 

    jQuery.fn.autolink = function() { 
     return this.each(function() { 
      //URLs starting with http://, https://, or ftp:// 
      var re = /((http|https|ftp):\/\/[\w?=&.\/-;#~%-\{\}$!|]+(?![\w\s?&.\/;#~%"=-]*>))/g; 
      $J(this).html($J(this).html().replace(re, '$1 ')); 
     }); 
    } 

+0

你試過已經不錯了,或者你只是不知道如何下手? – 2013-04-10 07:38:29

+0

@roXon是的。我用正則表達式來嘗試,但我無法得到正確的解決方案。我更新了我的問題與jquery函數 – Santhanakumar 2013-04-10 08:49:30

回答

0

嘗試這樣的事情。這將修改超鏈接的href屬性和html。

$("a").each(function(k,v){ 
    this.attr("href","http://"+this.attr("href")); 
    this.html("http://www."+this.html()+".com"); 
}) 
+0

不完全相同。 OP正在詢問如何識別來自頁面內容的任何類型的URL並將它們轉換爲「真實」鏈接。 – 2013-04-10 07:39:13

+0

@Fahim我需要在HTML內容中找到url。它可能包含palin文本url以及格式化的錨標籤。所以我需要鏈接純文本url的唯一。 – Santhanakumar 2013-04-10 09:05:03

0

使用該功能,並通過你的錨文本標記URL作爲URLNAME和HREF作爲鏈接名稱

function replaceURLWithHTMLLinks(urlname, linkname) { 

if (linkname && !linkname.match(/^http([s]?):\/\/.*/)) { 
    linkname = 'http://' + linkname 
} 
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i; 
return linkname.replace(exp,"<a href='$1'>"+urlname+"</a>"); 

}

相關問題