2013-05-30 15 views
0

我在寫一個函數來檢查輸入的字符串是否是Javascript中的url。我應該使用子字符串(0,6)並查看是否以「http://」開頭?或者有更好的方法來實現?乾杯。關於檢查字符串是否是Javascript中的URL的函數

+1

http://stackoverflow.com/questions/5717093/check-if-a-javascript-string -is-an-url – chuthan20

回答

0

你可以使用:

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

取決於你想要如何具體得到它。我相信你可以找到一個正則表達式,它會在這裏進行搜索。

+0

thx。恩..如果有人把https://怎麼樣?我想我需要包括一個OR語句。 – Alex

+0

沒有必要downvote,我指出了正則表達式的使用。 – Gabe

1

像這樣的東西應該處理的簡單情況:

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

用正則表達式:

/^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); 
1

你可以使用正則表達式

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

我覺得正則表達式是一個更好的解決方案:

function isAnUrl(url){ 

    var expression = /[[email protected]:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[[email protected]:%_\+.~#?&//=]*)?/gi; 

    var regex = new RegExp(expression); 

    if (url.match(regex)) 
    return true; 
    else return false; 
} 
相關問題