const regex = new RegExp('^(?P<scheme>http(?:s)?:\\/\\/)?(?P<www>www\\d?\\.)?(?P<domain>\\b(?!www\\d?\\.)[a-z\\d\\-]+(?:\\.[a-z\\d\\-]{2,})+)(?P<port>:\\d{1,5})?(?P<path>\\/(?:[-a-zA-Z0-9._~!$&\\\\'()*+,;=:@]|%[0-9a-fA-F]{2})*)*(?P<query_fragm>[?#&][\\/\\_\\-\\&\\%\\?\\#\\+\\=\\.:a-zA-Z\\d]*)*$', 'gm')
const str = `http://example.com
https://www.example.com
http://example.com/path
https://www.example.com/path
http://example.com/path?query=1
https://www.example.com/path?query=1
http://example.com/path#fragment
https://www.example.com/path#fragment
http://example.com:8080
https://www.example.com:8080
http://subdomain.example.com
https://www.subdomain.example.com
http://subdomain.example.com/path
https://www.subdomain.example.com/path
http://subdomain.example.com/path?query=1
https://www.subdomain.example.com/path?query=1
http://subdomain.example.com/path#fragment
https://www.subdomain.example.com/path#fragment
http://subdomain.example.com:8080
https://www.subdomain.example.com:8080
http://example.org
https://www.example.org
http://example.org/path
https://www.example.org/path
http://example.org/path?query=1
https://www.example.org/path?query=1
http://example.org/path#fragment
https://www.example.org/path#fragment
http://example.org:8080
https://www.example.org:8080
http://subdomain.example.org
https://www.subdomain.example.org
http://subdomain.example.org/path
https://www.subdomain.example.org/path
http://subdomain.example.org/path?query=1
https://www.subdomain.example.org/path?query=1
http://subdomain.example.org/path#fragment
https://www.subdomain.example.org/path#fragment
http://subdomain.example.org:8080
https://www.subdomain.example.org:8080
http://example.net
https://www.example.net
http://example.net/path
https://www.example.net/path
http://example.net/path?query=1
https://www.example.net/path?query=1
http://example.net/path#fragment
https://www.example.net/path#fragment
http://example.net:8080
https://www.example.net:8080`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions