regex match domain name in a url in javascript

To regex match the domain name in a URL using JavaScript, you can use the following regular expression:

index.tsx
const url = "http://www.example.com/index.html";
const regex = /\/\/([\w\d\.-]+)/;
const match = regex.exec(url);
const domainName = match[1];
console.log(domainName); // Output: "www.example.com"
197 chars
6 lines

This regex pattern matches the domain name portion of the URL after the // and before any subsequent / or query string. The [\w\d\.-]+ matches any combination of word characters (letters, digits or underscores), dots, and hyphens.

The exec() method of the regex object returns an array with the first element being the matched substring and subsequent elements being any captured groups. In this case, the domain name is captured by enclosing the [\w\d\.-]+ pattern in parentheses.

Finally, we access the domain name by getting the second element of the match array (match[1]) which corresponds to the first (and only) captured group.

gistlibby LogSnag