For example:
You have this string: var x = "/windows/far/away/foo.jpg"
How I now if that string is a URL or no?
What I need to do is:
if (x.charAt(0) == '/') {
x = "http://www.example.com/" + x;
}
else {
x = "http://www.example.com/one/two/three" + x;
}
The problem here is: What will happens when x will be a URL? like:
x = "http://www.externalpage.com/foo.jpg";
As you can see, x.charAt(0)
is 'h'
and the result will be:
http://www.example.com/one/two/threehttp://www.externalpage.com/foo.jpg
Now, the solution "maybe" like this:
if (is_valid_url( x )) {
....
}
else {
....
}
I'm using this function for this:
function is_valid_url(str) {
var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
'(\#[-a-z\d_]*)?$','i'); // fragment locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}
But this function only works with http and https, this will not work with other schemes like ftp or another....
I hope you understand the problem and bring me a solution. Thanks.