例如:
你有这个字符串:var x = "/windows/far/away/foo.jpg"
如果该字符串是 URL 还是不是,我现在该怎么办?
我需要做的是:
if (x.charAt(0) == '/') {
x = "http://www.example.com/" + x;
}
else {
x = "http://www.example.com/one/two/three" + x;
}
这里的问题是:当 x 是 URL 时会发生什么?像:
x = "http://www.externalpage.com/foo.jpg";
如您所见,x.charAt(0)
是 'h'
,结果将是:
http://www.example.com/one/two/threehttp://www.externalpage.com/foo.jpg
现在,解决方案“也许”是这样的:
if (is_valid_url( x )) {
....
}
else {
....
}
我正在使用此函数:
function is_valid_url(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 locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}
但是这个函数只适用于http和https,这不适用于其他方案,如ftp或其他......
希望您能理解问题并给我一个解决方案。谢谢。
最佳答案
要使其与其他协议(protocol)一起使用,只需将模式中的 https?
替换为与您想要的任何协议(protocol)匹配的表达式,例如:
var pattern = new RegExp('^((http|https|ftp|gopher|ssh|telnet):\/\/)?'+ // protocol
关于javascript - JavaScript 中检测字符串是否不是 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16295050/