0

I have this function that checks if the entered Url is valid. The problem is that I also need to know if this Url comes from facebook.com or not. If not the Url should not be considered as valid. How do I edit the function below to make it expects an Url with facebook.com string inside?

function isUrl(s) {

var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
return regexp.test(s);
}

5 Answers 5

4

Don't just test if facebook.com is in the string, cause it can be pretty much anywhere in the string e.g. in the query string.

This should match any facebook.com domain (and subdomains like mail.facebook.com). I also modified it a bit so it a bit more precise.. (not perfect though, but you should manage from here).

var regexp = /(ftp|http|https)(:\/\/)(www\.)?([a-zA-Z0-9]+\.)*(facebook\.com)(:[0-9]+)?(\/[a-zA-Z0-9]*)?/ ;
Sign up to request clarification or add additional context in comments.

Comments

1

Change your return statement to this:

return s.indexOf("facebook.com") > -1 && regexp.test(s);

Comments

1

Something like this is less complex to do using String#indexOf():

function isUrl(s) {

    if((s.indexOf("facebook.com")!=-1) || (s.indexOf('?facebook.com=') != -1) || 
         (s.indexOf('&facebook.com=') != -1))
   {
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-     \/]))?/
        return regexp.test(s);
   }
   else
     return false;
    }

Comments

0
function isUrl(s) {

  var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
  return regexp.test(s) && s.indexOf('facebook.com') > -1;
}

see String#indexOf

hint: i wouldnt modify my isUrl-method, because if you need this function for another url, it where anything other than facebook is allowed too. i would break it down into this code:

function isUrl(s) {
  var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
  return regexp.test(s);
}

function isFacebookUrl(s) {
  return isUrl(s) && s.indexOf('facebook.com') > -1;
}

1 Comment

of course it is not the ideal solution, and you mentioned it in your answer. but if he is sure that he will not have facebook.com inside the query string, my answer is probably the easiest and cleanest solution, i for myself upvoted your answer, because its the 'correct' one
0

You could modify the regex .... Or a quick and dirty solution could be... Check if URL starts with http://facebook.com before using the regex. Of course you would want to cover https as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.