No need to write a regex when the ability to parse URLs already exist.
const url = new URL("https://stackoverflow.com/questions/ask");
console.log(`${url.origin}`); // Includes port
console.log(`${url.protocol}//${url.hostname}`); // Alternatively...
2
solved How can I extract an actual URL from a string? [duplicate]