在Javascript中检查字符串是否为url的函数

A function on checking if the string is a url in Javascript

本文关键字:url 函数 是否 字符串 Javascript 检查      更新时间:2023-09-26

我正在编写一个函数来检查输入字符串是否为Javascript中的url。我应该使用子字符串(0,6),看看是否以"http://"开始?还是有更好的实现方式?欢呼。

这样的代码应该可以处理简单的情况:

function is_url(url) {
    return Boolean(url.match(/^https?:'/'//));
}

您可以使用正则表达式

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

您可以使用:

if(myvalue.indexOf('https://') == 0 || myvalue.indexOf('http://') == 0)

这取决于你想让它有多详细。我相信你可以在这里找到一个正则表达式你可以搜索一下

With regex:

/^http:/.test("http://example.com/")

如果您也想检查www: /^(http:|www'.)/.test("http://example.com/")

要与众不同:

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

我认为regex是一个更好的解决方案:

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