Javascript URI 正则表达式:如果 URL 有效,则将 http://、https://、ftp:// 替换为空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8802715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:34:42  来源:igfitidea点击:

URI Regex: Replace http://, https://, ftp:// with empty string if URL valid

javascriptjqueryregexurivalidation

提问by jQuerybeast

I have a simple URL validator. The url validator works as probably every other validator.

我有一个简单的 URL 验证器。url 验证器可能像其他所有验证器一样工作。

Now I want, if the URL passed, take the https://, http:// and remove it for var b.

现在我想要,如果 URL 被传递,则使用 https://、http:// 并将其删除为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.

所以我所做的是我制作了另一个正则表达式,它捕获 https://、http://、ftp:// 等,并说如果 url 通过了长时间测试,则获取第二个测试并将其替换为空字符串。

Here is what I came up with:

这是我想出的:

$("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')
   }

});

Why this doesn't work?

为什么这不起作用?

回答by YuS

var b = url.substr(url.indexOf('://')+3);

回答by Alnitak

protomatch.test()returns a boolean, not a string.

protomatch.test()返回一个布尔值,而不是一个字符串。

I think you just want:

我想你只是想要:

var protomatch = /^(https?|ftp):\/\//; // NB: not '.*'
...
var b = url.replace(protomatch, '');

FWIW, your matchregexp 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.

FWIW,您的正则match表达式完全无法理解,而且几乎肯定是错误的。它可能不允许国际化域,但它很难阅读,我无法确定。

回答by cregox

If you want a more generic approach, like Yuri's, but which will work for more cases:

如果您想要更通用的方法,例如 Yuri 的方法,但适用于更多情况:

var b = url.replace(/^.*:\/\//i, '');

回答by Tom

There may be an empty protocol, like: //example.com, so relying on '://' may not cover all cases.

可能有一个空协议,例如://example.com,因此依赖 '://' 可能无法涵盖所有​​情况。