javascript - URL/字符串的正则表达式 - 如果协议返回 false
问题描述
尝试创建一个字符串不应以 http(s)://、http(s)://www 开头的正则表达式。字符串的其余部分可以是任何东西。
我使用了这个 regeg,但如果我们有,它会返回 truehttp://
^(http://www.|https://www.|http://|https://)?[a-z0-9]+([-.]{1}[a-z0-9]+)*.[a-z]{2,5}(:[0-9]{1,5})?(/.*)?$
我试过的另一个是
var re = new RegExp("(http|https|ftp)://");
var str = "http://xxxx.com";
var match = re.test(str);
console.log(match);
这一个也回归真实。
演示在这里
let re = /(http|https|ftp):///;
let url = 'xxxx.xxxx.xxxx'; // this is valid but test returns false
let url2 = 'https://www.xxzx.com/xxx.aspx'; // this should fail as there is https://www in url
console.log(re.test(url)); //
console.log(re.test(url2)); //
这可以用正则表达式吗?
解决方案
您需要在正则表达式中使用负前瞻来丢弃以http
or https
or等协议开头的字符串ftp
。你可以使用这个正则表达式,
^(?!(?:ftp|https?):\/\/(www\.)?).+$
JS 演示,
const arr = ['xxxx.xxxx.xxxx','ftp://www.xxzx.com/xxx.aspx','https://www.xxzx.com/xxx.aspx','http://xxxx.com','https://xxzx.com/xxx.aspx','http://www.xxxx.com']
arr.forEach(s => console.log(s + " --> " + /^(?!(?:ftp|https?):\/\/(www\.)?).+$/.test(s)))
推荐阅读
- python - 为什么 python 中的类或列表具有 id() 但具有不同的变量
- .htaccess - .htaccess 仅在参数存在时重定向
- java - 调用 stop() 时 Jcoserver 状态更改为 STOPPING(不是 STOPPED)
- node.js - api 响应包含转义字符
- vb.net - 针对性别的 LINQ 查询过滤
- javascript - C# UWP 中的发射格式
- c++ - 用于取消标志的 std::atomic_bool:std::memory_order_relaxed 是正确的内存顺序吗?
- angular - IE 浏览器和 Firefox Angular 5 材料输入延迟问题(通过创建一些记录使用该应用程序几分钟后延迟。)
- python - 平滑具有多条曲线的函数
- d3.js - 将图例添加到 dc.js 散点图