I'm struggling to find a reliable way to extract the Top-Level Domain from a URL. The challenge I'm facing is that the URLs entered by users can vary greatly - they might enter www.google.com, m.google.com, m.google.uk, google.uk, or www.m.google.com.
I attempted using the slice
method, but it didn't yield the desired results because some URLs contain 2 or 3 characters. Splitting based on "." also proved problematic as the number of resulting parts could be 2, 3, or even 4. Is there a JavaScript function available that can accomplish this in a single line? Are there any convenient custom functions to tackle this?
Most resources suggest retrieving the host name, but my goal is to specifically isolate the last 2 or 3 characters of the URL (such as com, uk, cn, etc.). While I could implement multiple if-else loops, I'd prefer a simpler solution that avoids this level of complexity.
I aim to obtain an output like 'com', 'uk', or 'cn' depending on the top-level domain in the URL. Since users input the URL, predicting whether they will type m.google.com, www.m.google.com, www.google.com, or simply google.com adds an additional layer of uncertainty.