To regex match the domain name in a URL using JavaScript, you can use the following regular expression:
index.tsx197 chars6 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