Reputation:
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);
}
Upvotes: 0
Views: 2821
Reputation: 12755
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]*)?/ ;
Upvotes: 4
Reputation: 49432
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;
}
Upvotes: 1
Reputation: 14434
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;
}
Upvotes: 0
Reputation: 10243
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.
Upvotes: 0
Reputation: 5768
Change your return statement to this:
return s.indexOf("facebook.com") > -1 && regexp.test(s);
Upvotes: 1