1

I have a div that contains paragraphs elements with text inside. Sometimes this text can be a link which I want to store in a var. I only want to select the link text, not the paragraph and not the div.

So here is an example of the 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 I do this:

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

The problem is that I don't know how to select just the link text - it ends up selecting the entire <p> or <div>. The rules of a link are that it either begins with http or www and it has no spaces in it whatsoever. So I want to select just the string that contains http or www that has to spaces in it.

It sounds simple but I'm stuck!

volume one
  • 6,800
  • 13
  • 67
  • 146
  • 1
    http://stackoverflow.com/questions/4504853/how-do-i-extract-a-url-from-plain-text-using-jquery .. and about if statement use $("div > p:contains('http')") – Mohamed-Yousef Dec 05 '15 at 16:04
  • I think you are looking for this http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links – Elec Dec 05 '15 at 16:13

1 Answers1

2

Since you already able to select the entire <p> or <div>, how about split the text within it and test them one by one?

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

Or,

You can try String.prototype.match() with regular expression. It will return an array of matched strings.

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"]
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
xhg
  • 1,850
  • 2
  • 21
  • 35