检查 JavaScript 字符串是否为 URL [英] Check if a JavaScript string is a URL
本文介绍了检查 JavaScript 字符串是否为 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
JavaScript 中有没有办法检查字符串是否是 URL?
Is there a way in JavaScript to check if a string is a URL?
RegEx 被排除,因为 URL 很可能像 stackoverflow
那样写;也就是说,它可能没有 .com
、www
或 http
.
RegExes are excluded because the URL is most likely written like stackoverflow
; that is to say that it might not have a .com
, www
or http
.
推荐答案
一个相关问题的答案:
或者来自 Devshed:
function validURL(str) {
var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
'(\#[-a-z\d_]*)?$','i'); // fragment locator
return !!pattern.test(str);
}
这篇关于检查 JavaScript 字符串是否为 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文