spez
spez

Reputation: 469

Regex for valid host:port form in JavaScript

I did't found yet somethig that fits to my need, I need a regex that varify host:port.

for example:

localhost:52247  //true
web.mycompany.com //true
web.mycompany.com:52247 //true
192.168.108.76:8383/ //true
192.168.108.76/ //true

and should return false for the following;

localhost:9999999  //false because port is not valid
'' //false becuse string is empty
web.mycoעעעעעmpany.com:52247 //false because it contains hebrew characters
192.168.377.76:8383/ //false because ip address not valid

Upvotes: 0

Views: 761

Answers (1)

C3roe
C3roe

Reputation: 96417

I would not write my own regular expression here, but use the URL() constructor - that will throw a TypeError exception, if the provided parameter is not considered a valid URL.

Your input values would just have to be prefixed with a protocol, to make them valid, non-relative URLs in the first place - so let’s just put http:// in front, and then see if the constructor throws an exception, or not:

var urls = 'localhost:52247,web.mycompany.com,web.mycompany.com:52247,192.168.108.76:8383/,192.168.108.76/,localhost:9999999,,web.mycoעעעעעmpany.com:52247,192.168.377.76:8383/'.split(',');

urls.forEach(function(e){
  try {
    new URL('http://'+e);
    console.log(e + ": true");
  }
  catch(x) {
    console.log(e + ": false");
  }
})

Upvotes: 2

Related Questions