URI正则表达式:如果URL有效,则用空字符串替换http://,https://,ftp:// [英] URI Regex: Replace http://, https://, ftp:// with empty string if URL valid

查看:291
本文介绍了URI正则表达式:如果URL有效,则用空字符串替换http://,https://,ftp://的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

现在我想要,如果传递了URL,请使用https://,http://并将其删除 var b

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

所以我做的是我做了另一个正则表达式,它捕获https://,http ://,ftp://等,并说如果url通过了长测试,请进行第二次测试,并用空字符串替换它。

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.

这是我来的up with:

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')
   }

});

为什么这不起作用?

推荐答案

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

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

我想你只是想:

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

FWIW,你的匹配 regexp完全不可穿透,几乎肯定是错的。它可能不允许国际化的域名,但它很难读,我无法确定。

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.

这篇关于URI正则表达式:如果URL有效,则用空字符串替换http://,https://,ftp://的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆