Javascript检测TAG中的完整URL

Javascript Detect Full URL in TAG

本文关键字:URL 检测 TAG Javascript      更新时间:2023-09-26

我希望javascript检测图像的来源,并使用REGEX 对其是否为完整URL采取行动

示例代码:

var source = 'http://test.com/';
if( [if var source starting with http:// ] ){ // Regex conditional
    // do something
}else{
    // // something
}

如何使用Javascript正则表达式做到这一点?

谢谢。。。

如果你坚持Regex:

^https?:'/'/.*$

要在此处测试的Javascript代码:

  var re = /^https?:'/'/.*$/;
  var sourcestring = "source string to match with pattern";
  var matches = re.exec(sourcestring);
  for (var i=0; i<matches.length; i++) {
    alert("matches["+i+"] = " + matches[i]);
  }

对于您的代码:

var source = 'http://test.com/';
var pattern = /^https?:'/'/.*$/;
if(null != pattern.exec(source))
{ 
    // Regex conditional
    // do something
}
else
{
    // // something
}

但请注意,这只检查URL的第一部分,这可能并不一定意味着字符串的其余部分符合URL。例如,您的源字符串可以是类似于"http://^&#*@%.IAmABadUrl.com"的内容,如果未编码发送,则该内容不是有效的URL
关于IETF网站上URL中允许的内容的更多信息:

因此,只有字母数字、特殊字符"$-_.+!*'()"和可以使用用于保留目的的保留字符在URL中未编码。

为什么不使用

if(source.indexOf("http://")>-1){
//do something?
}