I am writing a function to check if the input string is a url in Javascript. Should I use substring(0,6) and see if starts with "http://"? Or there is a better way to achieve? Cheers.
Asked
Active
Viewed 331 times
0
-
1http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-an-url – chuthan20 May 30 '13 at 21:22
5 Answers
1
You could use:
if(myvalue.indexOf('https://') == 0 || myvalue.indexOf('http://') == 0)
Depends how detailed you want to get with it. I am sure you can find a regex that would do it on here is you searched around.

Gabe
- 49,577
- 28
- 142
- 181
-
thx. Um.. How about if somebody puts https://? I guess I would need to include an OR statement. – Alex May 30 '13 at 21:28
-
1
Something like this should handle the simple cases:
function is_url(url) {
return Boolean(url.match(/^https?:\/\//));
}

Blender
- 289,723
- 53
- 439
- 496
1
With regex:
/^http:/.test("http://example.com/")
If you wanted to check www
too: /^(http:|www\.)/.test("http://example.com/")
And to be different:
function matchString(str,matches)
{
if(matches)
{
matchString.toCheck=matches;
}
var matched = [];
for(var i=[0,str.length];i[0]<i[1]; i[0]++)
{
for(var j=[0,matchString.toCheck.length];j[0]<j[1]; j[0]++)
{
if(!matched[j[0]])matched[j[0]]={c:0,i:-1};
if(matchString.toCheck[j[0]][matched[j[0]].c]==str[i[0]])
{
matched[j[0]].c++;
if(matched[j[0]].i==-1)matched[j[0]].i=i[0];
}
else if(matchString.toCheck[j[0]].length!=matched[j[0]].c)matched[j[0]]={c:0,i:-1};
}
}
return matched;
}
var urlVariants = matchString("https://",["http://","https://","www."]);
var isUrl = false;
for(var i=[0,urlVariants.length]; i[0]<i[1]&&!isUrl; i[0]++)
{
isUrl = (urlVariants[i[0]].i==0);//index at the start
}
console.log(isUrl);

Isaac
- 11,409
- 5
- 33
- 45
0
I think regex is a better solution:
function isAnUrl(url){
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (url.match(regex))
return true;
else return false;
}

gal007
- 6,911
- 8
- 47
- 70