2015-12-05 39 views
1

我有一個div,其中包含帶有文本的段落元素。有時這個文本可以是我想要存儲在var中的一個鏈接。我只想選擇鏈接文本,而不是段落而不是div。如何選擇包含特定字母的文本

因此,這裏是HTML的一個例子

<div> 
    <p>I have found a good review of a TV here <br> 
    https://www.avforums.com <!-- I want to select this text ---> <br> 
    This seems good to me! 
    </p> 
</div> 

如果我這樣做:

if ($("div:contains('http')") || $("div:contains('www')")) { 
var extractedLink = // select the link text and store it here 
} 

的問題是,我不知道如何選擇只是鏈接文本 - 它結束選擇整個<p><div>。鏈接的規則是它以http或www開頭,而且它沒有任何空格。所以我想只選擇包含http或www的字符串,它必須包含空格。

聽起來很簡單,但我卡住了!

+1

http://stackoverflow.com/questions/4504853/how-do-i-extract-a-url-from-plain-text-using-jquery ..和有關if語句使用$(「DIV > p:包含('http')「) –

+0

我認爲你正在尋找這個http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links – Elec

回答

2

既然您已經能夠選擇整個<p><div>,那麼將其中的文本分割並逐個測試它們呢?

var sentences = $(???).text().split(" "); 
for (var i...) { 
    var sentence = sentences[i]; 
    if (sentence.substr(0, 4) == "http" || ...) { 
     // found! 
    } 
} 

或者,

你可以嘗試用String.prototype.match()正則表達式。它將返回一個匹配的字符串數組。

var str = "http://www www.www www.x www.google.com/www_hey are a famous website while http is not" 
matches = str.match(/(\bhttp|\bwww)\S+/gi); 
// matches = ["http://www", "www.www", "www.x", "www.google.com/www_hey"] 
+0

去匹配(url_regex)'... – xtofl

相關問題