I want a regular expression for javascript to validate host address like
开发者_开发百科http://192.168.10.10:8089/
and
www.abc.com
and
www.abc.com.aa
Have you tried looking for it at Regular Expression Library?
This puts a valid numeric IP address in $1
:
/(\bhttp:\/\/(?:\d{1,2}\.|1\d\d\.|2[0-4]\d\.|25[0-5]\.){3}(?:1?\d?\d|2[0-4]\d|25[0-5])\b(?::\d{1,5})?)/
If you don't care about validation, you can use \d{1,3}\
. for the numbers that precede a period and \d{1,3}
for the last one. This will run faster.
For the "www
" URLs, this will put the URL in $1
:
/(www\.\w+\.\w{3}(?:\.\w{2})?)\b/
Am using documentation here:
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions
This block of code will decompose the url
var fields = url.match( /(.*)[:/]{3}([^:/]+)[:]?([^/]*)([^?]*)[?]?(.*)/ );
if(fields === null){
throw new Error('bar url');
}
var protocol = fields[1];
var host = fields[2];
var port = fields[3];
var path = fields[4];
var query = fields[5];
So if you get into the if, means that url is a bad composed url
Hope it helps
精彩评论