0

Possible Duplicate:
Check if a Javascript string is an url

I am not very familiar with RegEx so it would be great if you could help me solve this problem.

I need a JS function that will:

  1. Check for the string (textarea input) if it has any url.
  2. If yes - search for the first url found and return array(true,url)
  3. If no - return array(false,"")

The problem I am having is this pattern that validates input.

function _is_url(url) {
    var pattern = /(((ht|f)tps?\:\/\/)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5})(:[\d]{1,5})?))\S+/i;
    var result = new Array();
    var testing = pattern.test(url);
    if(testing) {
        var newurl = url.match(pattern);
        result[0] = true;
        result[1] = newurl[0];
        console.log(result[1]);
    }
    else {
        result[0] = false;
        result[1] = "";
    }

    return result;
}

With this pattern, testing == true even if the url is http://www.youtube which is not a valid url.

What I need is to check the full url: http://www.youtube.com and any other url.

Community
  • 1
  • 1
Nikola R.
  • 1,173
  • 6
  • 23

1 Answers1

0

Remove the \S+ after your expression to exclude www.youtube, and add a word boundary \b. Also {1} after the first letter can be omitted.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • In the console.log(result[1]), im still getting http://www.yo http://www.you http://www.yout ... http://www.youtube.com – Nikola R. Dec 12 '12 at 00:15
  • `/(((ht|f)tps?\:\/\/)?([a-zA-Z]([\w\-]+\.)+([\w]{2,5})(:[\d]{1,5})?))\b/i` works for me. Please show me a demo with your inputs. Btw, `.yo` or `.you` might really be valid TLDs. – Bergi Dec 12 '12 at 00:19
  • you missunderstood my question or I didn't write it good. The thing is that ht tp://youtu is not a valid url while ht tp://youtu.be IS a valid url. I want to check only for valid url's which htt p://face or htt p://goo is not – Nikola R. Dec 12 '12 at 00:21
  • Your pattern works great if we're writting htt p://domain without WWW but if I write htt p://www.you - it will say it's true. So the only thing is missing checking for www and ignoring it as a domain name. – Nikola R. Dec 12 '12 at 00:23
  • I am so close, only thing left is making this (www.?) optional: /(((ht|f)tps?\:\/\/)?(www.?)([a-zA-Z]([\w\-]+\.)+([\w]{2,5})(:[\d]{1,5})?))\b/i – Nikola R. Dec 12 '12 at 00:28
  • `www.you` is a uncommon, but valid domain. Please tell us before what you want :-) You should be able to ignore `www` parts by inserting `(www\.)?(?!www\.)` after the protocol part. – Bergi Dec 12 '12 at 00:29
  • http://jsfiddle.net/u7PNn/4/ Please take a look – Nikola R. Dec 12 '12 at 00:38
  • Taken a look, nothing happens. A self-executing example would have been better :-) No really, I tried the pastes you provided, and they work with my pattern. – Bergi Dec 12 '12 at 00:44