0

I have this regex, which extracts domain name from string.

var matches = str.match(/^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i);

I would like the same RegEx, including other protocols like rstp. For example:

"http://www.example.com/a/".match(/^https?\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i)

Result: ["http://www.example.com/", "www.example.com"]

I have tried this:

"http://www.example.com/a/".match(/^(http|https|rtsp)\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i)

But it returns http too: ["http://www.example.com/", "http", "www.example.com"]

I would like the same output.

Thanks.

1 Answer 1

2

You just need to turn your group of protocol alternations into a non-capturing group by prefixing it with ?::

"http://www.example.com/a/".match(/^(?:http|https|rtsp)\:\/\/([^\/:?#]+)(?:[\/:?#]|$)/i)
//["http://www.example.com/", "www.example.com"]
Sign up to request clarification or add additional context in comments.

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.