2011-05-07 34 views
2

我想解析一些字符串,並且它嵌入了一些http鏈接。我想使用jQuery在這個字符串中動態創建錨標籤,然後在前端顯示它們,以便用戶可以點擊它們。認識到http鏈接和創建錨標記

有沒有辦法做到這一點?

謝謝!

+0

顯示想要解析的示例字符串將有助於人們更好地引導您。 – sahaj 2011-05-07 07:55:16

回答

7

你可以這樣說:

$(function(){ 
    //get the string 
    var str = $("#text").html(); 
    //create good link matching regexp 
    var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/g 
    // $1 is the found URL in the text 
    // str.replace replaces the found url with <a href='THE URL'>THE URL</a> 
    var replaced_text = str.replace(regex, "<a href='$1'>$1</a>") 
    //replace the contents 
    $("#text").html(replaced_text); 
}); 

working example

+0

你能告訴我這是什麼意思嗎? – locoboy 2011-05-09 07:20:16

+0

這就是爲什麼我寫了評論,什麼你不明白? – Teneff 2011-05-09 07:51:44

+0

只要試着去理解這個語句的含義是什麼意思就是'regex = /(https?:\/\ /([ - \ w \。] +)+(:\ d +)?(\ /([\ w \/_ \。 ] *(\?\ S +)?)?)?)/ g'。看起來很神祕。當你說'$(「#text」)。html(str.replace(regex,「$1」));' – locoboy 2011-05-09 19:57:15