问题描述
您好,我想验证 www.google.com 或 或 google.com ,是否可以实现,如果是这样,请在javascript中共享解决方案。
请注意我只希望底层协议是HTTP或HTTPS morover现在的主要问题是如何在Javascript中使用单个正则表达式映射所有这三个模式,它不必检查页面是否是是否有效,如果用户输入的值与上面列出的三个案例中的任何一个匹配,则另一方面它应该返回true,如果它没有它应该返回fasle。
Hi there i want to validate url of the types www.google.com or http://www.google.com or google.com using a single reguar expression,is it achievable,if so, kindly share solution in javascript.Please note i only expect the underlying protocols to be HTTP or HTTPS morover the main question on hand is how can we map all these three patterns using one single regex expression in Javascript it doesn't have to check whether the page is active or not,if the value entered by user matches any of the above listed three case it should return true on the other hand if it doesnt it should return fasle.
推荐答案
检查URL是否实时
这有点像黑客,但如果我需要这样做,这就是我接近它的方式:
Checking if a URL is live
This is a bit of a hack, but if I required to do so, this is how i would approach it:
从给定网址解析并提取域名/ IP
Parse and extract the domain/ip from the given url
这是在nodejs中执行此操作的方法:
This is how to do that in nodejs:
var url = require("url");
var result = url.parse('http://drive.google.com/0/23');
console.log(result.hostname);
第二步
ping 提取的域/ ip - 由于网络配置的原因,并非所有服务器都会响应ICMP(PING)请求。
2nd step
ping the extracted domain/ip - not all servers will respond to ICMP (PING) requests due to network configuration.
var ping = require ("net-ping");
var session = ping.createSession ();
session.pingHost (target, function (error, target) {
if (error)
console.log (target + ": " + error.toString ());
else
console.log (target + ": Alive");
});
- 退房 net-ping package
- check out net-ping package
您可以对该网址执行HTTP HEAD请求并检查状态代码。
You can perform an HTTP HEAD request to that url and check the status code.
var request = require('request');
request({method: 'HEAD', uri:'http://www.google.com'}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
- 如果这是一个Web服务(因为您可以触发操作),这有点冒险。
- 如果网址需要身份验证/重定向会更复杂
- @JanJůna评论说最好使用HEAD。他完全正确。请注意,并非所有Web服务器都支持
HEAD
方法 - 查看 package
- It's a bit risky if this is a web-service (since you can trigger actions).
- Would be more complicated if the url requires authentication / redirection
- @Jan Jůna commented that it's better to use HEAD. He's completely right. Note that not all web servers support
HEAD
method - Check out the request package
您可以使用名为
You can use the existing nodejs package called validUrl
用法:
var validUrl = require('valid-url');
var url = "http://bla.com"
if (validUrl.isUri(url)){
console.log('Looks like an URI');
}
else {
console.log('Not a URI');
}
安装:
npm install valid-url --save
如果你还想要一个简单的REGEX
谷歌是你的朋友。
这篇关于验证Node.js中的Url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!