gpt4 book ai didi

Javascript 检测 TAG 中的完整 URL

转载 作者:行者123 更新时间:2023-12-02 19:23:30 25 4
gpt4 key购买 nike

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

示例代码:

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

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

谢谢...

最佳答案

如果您坚持使用正则表达式,那么就可以了:

^https?:\/\/.*$

要测试的Javascript代码here :

  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://^&#*@%.IAmAadUrl.com”,如果未编码发送,则不是有效的 URL。
有关 URL 中允许的内容的更多信息,请访问 IETF website :

Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

关于Javascript 检测 TAG 中的完整 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12268823/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com