Dangur
Dangur

Reputation: 139

RegExp to validate URL with port or IP with PORT (JS)

I need a robust RegExp that validates URL with port or IP with PORT e.g

http://123.456.78.900:4200 > true

http://something:4200 > true

I searched but didn't find an expression that checks both

isUrlValid(input) {
  const regex = '^((https:|http:|[/][/]|www.)([a-z]|[A-Z]|[:0-9]|[/.])*)$'​;
  const url = new RegExp(regex, 'g');
  return url.test(input);
}

Upvotes: 0

Views: 6531

Answers (3)

Murik
Murik

Reputation: 145

Try this

^(https?:\/\/[\w.-]+:?\d*)

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37765

Try this

^((https?:\/\/)|(www.))(?:([a-zA-Z]+)|(\d+\.\d+.\d+.\d+)):\d{4}$
  • ^ - Anchor to start of string.
  • ((https?:\/\/)|(www.)) -Matches http:// or https:// or www..
  • (?:([a-zA-Z]+)|(\d+\.\d+.\d+.\d+))
    • ?:- Makes group non-capturing.
    • ([a-zA-Z]+)- Matches any alphabets one or more time (add 0-9 if you want digits too).
    • | : Alternation works as logical OR.
    • (\d+\.\d+.\d+.\d+)- Matches digit format for IP address.
  • :\d{4} - Will match 4 digit number this you can adjust as per your use case.
  • $ - Anchor to end of string.

click here for demo

P.S - For performance you can make groups as non-capturing group by using ?: at start. i intentionally not added them for the sake of readability.

Upvotes: 2

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92657

Try this

^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+:\d*

Your second domain not contains dot for this case - i have this

^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)*:\d*

Upvotes: 0

Related Questions