0

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.

1

5 Answers 5

1

Something like this should handle the simple cases:

function is_url(url) {
    return Boolean(url.match(/^https?:\/\//));
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could use a regular expression

/^http:\/\//.test(urlString)

Comments

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.

2 Comments

thx. Um.. How about if somebody puts https://? I guess I would need to include an OR statement.
No need to downvote, i pointed out the use of regex.
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);

Comments

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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.