2012-07-02 90 views
0

我想下面的文本解析成格式化的URL與錨標記:解析文本格式與內容的網址,並縮短網址

something is wrong with http://www.gbin1.com/index.html, but cannot find the reason in http://www.google.com 

我怎麼能代替上面<a href="url">url</a>文字的網址,並使用縮短JavaScript如下所示:

something is wrong with <a href="http://www.gbin1.com/index.html">gbin1.com</a>, but cannot find the reason in <a href="http://www.gbin1.com">google.com</a> 
+0

http://whathaveyoutried.com? – antyrat

+0

你嘗試過正則表達式嗎? – kevin628

+0

爲什麼第二個鏈接不會轉到Google?將Google文本鏈接到非Google網站似乎有點偷偷摸摸。 –

回答

2

檢查此解決方案。

var x = "something is wrong with http://www.gbin1.com/index.html, but cannot find the reason in http://www.google.com"; 
var expression = /[[email protected]:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[[email protected]:%_\+.~#?&//=]*)?/gi; 
var regex = new RegExp(expression); 
var split = x.split(" "); 
for(var i=0; i< split.length; i++){ 
    if(split[i].match(regex)){ 
     var text = split[i].split(".").slice(1).join(".").split("/")[0]; 

     split[i] = '<a href=\"' +split[i]+'\">'+text+'</a>'; 
    } 
} 
console.log(split.join(" ")); 

http://jsfiddle.net/4JGY7/

+0

發佈代碼,而不僅僅是一個鏈接。 – jbabey

+0

看起來不錯,但是url中有一個額外的逗號,如下所示:gbin1.com出錯,但找不到原因google.com terry

+0

替換此行 split [i] =''+text+''; 與 split [i] =''+text+''; – scusyxx