URI 正则表达式:如果 URL 有效,则将 http://、https://、ftp:// 替换为空字符串
我有一个简单的 URL 验证器。 url 验证器的工作方式可能与其他验证器一样。
现在我想要,如果 URL 通过,则获取 https://、http:// 并将其删除为 var b
。
所以我所做的是我制作了另一个正则表达式,它捕获 https://、http://、ftp:// 等,并表示如果 url 通过了长测试,则进行第二个测试并将其替换为空字符串。
这是我想到的:
$("button").on('click', function () {
var url = $('#in').val();
var match = /^([a-z][a-z0-9\*\-\.]*):\/\/(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)*(?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@)?(?:(?:[a-z0-9\-\.]|%[0-9a-f]{2})+|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]))(?::[0-9]+)?(?:[\/|\?](?:[\w#!:\.\?\+=&@!$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})*)?$/;
var protomatch = /^(https?|ftp):\/\/(.*)/;
if (match.test(url)) { // IF VALID
console.log(url + ' is valid');
// if valid replace http, https, ftp etc with empty
var b = url.replace(protomatch.test(url), '');
console.log(b)
} else { // IF INVALID
console.log('not valid')
}
});
为什么这不起作用?
I have a simple URL validator. The url validator works as probably every other validator.
Now I want, if the URL passed, take the https://, http:// and remove it for var b
.
So what I've done is I made a another Regex which captures https://, http://, ftp:// etc and say if the url passed the long test, get the second test and replace it with empty string.
Here is what I came up with:
$("button").on('click', function () {
var url = $('#in').val();
var match = /^([a-z][a-z0-9\*\-\.]*):\/\/(?:(?:(?:[\w\.\-\+!amp;'\(\)*\+,;=]|%[0-9a-f]{2})+:)*(?:[\w\.\-\+%!amp;'\(\)*\+,;=]|%[0-9a-f]{2})+@)?(?:(?:[a-z0-9\-\.]|%[0-9a-f]{2})+|(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]))(?::[0-9]+)?(?:[\/|\?](?:[\w#!:\.\?\+=&@!
Why this doesn't work?
~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})*)?$/;
var protomatch = /^(https?|ftp):\/\/(.*)/;
if (match.test(url)) { // IF VALID
console.log(url + ' is valid');
// if valid replace http, https, ftp etc with empty
var b = url.replace(protomatch.test(url), '');
console.log(b)
} else { // IF INVALID
console.log('not valid')
}
});
Why this doesn't work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
protomatch.test() 返回一个布尔值,而不是字符串。
我想你只是想:
FWIW,你的
match
正则表达式是完全难以理解的,而且几乎肯定是错误的。它可能不允许国际化域名,但它很难阅读,我无法确定。protomatch.test()
returns a boolean, not a string.I think you just want:
FWIW, your
match
regexp is completely impenetrable, and almost certainly wrong. It probably doesn't permit internationalised domains, but it's so hard to read that I can't tell for sure.如果您想要一种更通用的方法,例如 Yuri 的方法,但适用于更多情况:
If you want a more generic approach, like Yuri's, but which will work for more cases:
可能有一个空协议,例如://example.com,因此依赖“://”可能无法涵盖所有情况。
There may be an empty protocol, like: //example.com, so relying on '://' may not cover all cases.