0

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);
}

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Port number can have 1 to 5 digits. I think {1,5} would be better.
0

Try this

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

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

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

2 Comments

That doesn't match http://something:4200 :P It does match http://123.456.78.900:foobar, which also seems wrong.
I fix my answer
0

Try this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.