Search code examples
javascriptregexurlsubdomain

Regex to capture domain name from string including email addresses for specific tld's


I need regex that can parse domain names from strings including the domain from email addresses. I found the following regex on StackOverflow:

/(?:[\w-]+\.)+[\w-]+/

Which works famously according to the demo provided: https://regex101.com/r/aF1cY0/5

I got the regex from a different question on StackOverflow here:

How to get domain from a string using javascript regular expression

I'd like to change the existing regex to only match specific TLD's (e.g.. com|net|biz)

Since I'm a total newb to regex I'm having trouble figuring out where to put that stipulation.

Any help is greatly appreciated.


Solution

  • /(?:[\w-]+\.)+(?:com|net|biz)/i

    function check(){
      var str = prompt("URL example: ");
      var match = str.match(/(?:[\w-]+\.)+(?:com|net|biz)/i);
      if(match)
        alert("Your domain is: '" + match + "'");
      else
        alert("Sorry! Nothing matched!");
    }
    <button onclick="check()">TRY</button>