2011-09-23 58 views
2

將CONENT中的網址轉換爲可點擊並縮短。如何將內容中的網址轉換爲使用javascript的鏈接

例如:

轉換內容

Balabala The link is http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff 

Balabala The link is <a href=http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff>http://www.google.com/?aa...</a> 
+1

可能的重複[如何用鏈接替換普通URL?](http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links) – icktoofay

+0

@icktoofay這是一個不同的問題。該網址應該被縮短。 –

+0

['replace'](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace)可以使用一個函數,它可以截斷URL。就這樣說,我認爲問題是,如果不是*確切*重複,*非常相似。 – icktoofay

回答

-1

喜歡的東西:

len = 15; //set how long of a string you would like to show 

url = "http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff"; 

//if the original url is smaller than or equal to the length than do nothing 
//otherwise take the len number of chars and append ... after 
shorturl = (url.length <= len) ? url : url.substr(0,len) + "..."; 

link = "<a href='" + url + "'>" + shorturl + "</a>"; 
+1

但是如何在內容中找到網址? –

0

像這樣的東西可能會有所幫助:

<div id='result'> 
</div> 
<script> 
var content = "The link is http://www.google.com/?q=hello visit it!"; 
var result = content.replace(/(http:\/\/(www\.)?([^(\s)]+))/, "<a href='$1'>$3</a>"); 
document.getElementById('result').innerHTML = result; 
</script> 
0

這裏是一個替換字符串內的任何URL與錨的函數:

function linkify(str){ 
    var url = 'http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff'; 
    return str.replace(/https?\:\/\/\S+/, function(url){ 
     var shortUrl = url.substring(0, 20) + '...'; 
     return shortUrl.link(url) 
    }) 
} 

linkify("Balabala The link is http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff") 
// "Balabala The link is <a href="http://www.google.com/?aaaaabefaaaaaaaaaaaafeeafaeff3asefffffffffff">http://www.google.com/?aaaaabe...</a>" 

「剪切」長度可作爲第二個參數被傳遞。

+0

不要有這個假設。 –

相關問題