Fraz Sundal
Fraz Sundal

Reputation: 10448

Regular expression of host address?

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

Upvotes: 1

Views: 664

Answers (3)

luismesas
luismesas

Reputation: 352

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

Upvotes: 0

cheapwax
cheapwax

Reputation: 36

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

Upvotes: 1

Tomas Narros
Tomas Narros

Reputation: 13468

Have you tried looking for it at Regular Expression Library?

Upvotes: 1

Related Questions