我在寫一個函數來檢查輸入的字符串是否是Javascript中的url。我應該使用子字符串(0,6)並查看是否以「http://」開頭?或者有更好的方法來實現?乾杯。關於檢查字符串是否是Javascript中的URL的函數
0
A
回答
0
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;
}
相關問題
- 1. 檢查字符串是否是Spotify URL
- 2. 函數檢查字符串是否有
- 3. 在onClick函數中JavaScript檢查字符串是否爲空
- 4. 檢查字符串是否匹配url
- 5. 關於檢查字符串是否爲數字
- 6. 檢查一個字符串是否是JavaScript中的html字體
- 7. 檢查字符串是否是實數
- 8. 如何檢查NS字符串是否包含javascript函數?
- 9. 檢查字符串是否屬於xml
- 10. 檢查字符串是否不是Javascript中的空格
- 11. 檢查字符串是否是JavaScript中的迴文
- 12. 如何檢查var是否是JavaScript中的字符串?
- 13. JavaScript函數檢查字符串中是否只有數字或小數位
- 14. 如何檢查數組是否包含Javascript中的字符串?
- 15. Javascript函數來檢查字符串是否是有效的日期
- 16. 檢查字符串x是否等於字符串中的任何字符串[]
- 17. JavaScript/jQuery - 檢查字符串是否包含關鍵字
- 18. 檢查字符串是否有數字
- 19. 函數檢查字符串的第一個字符是否是一個字母
- 20. 如何檢查textField是否等於數組中的字符串
- 21. 如何檢查字符串是否是有效的HTTP URL?
- 22. 檢查輸入是否是C++中的數字或字符串
- 23. 如何檢查.NET中的字符串是否是數字?
- 24. 如何檢查url是否包含多個字符串。 Javascript/jquery
- 25. 檢查一個字符串的數字是否大於1
- 26. 如何檢查函數參數是否是perl中的字符串
- 27. 檢查字符串是否是Javascript的前綴RegExp
- 28. 檢查參數是否爲字符串
- 29. 檢查數組是否有字符串?
- 30. 檢查所有字符串值是否是DataTable字符串列中的整數
http://stackoverflow.com/questions/5717093/check-if-a-javascript-string -is-an-url – chuthan20