2015-12-05 30 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

相关问题