in js, how can i take only a domain and its tld in an arbitrary string that can contains…
- User
in js, how can i take only a domain and its tld in an arbitrary string that can contains anything, like query strings with domains, or sub-domains ?
- Assistant
Here are two common ways to pull out just the “registered” domain + TLD (for example, from
"Visithttps://sub.foo.example.co.uk/path?x=1"
you want"example.co.uk"):- Use a Public Suffix List parser (most reliable)
- Use a quick & dirty regex + URL approach (no extra deps, but less foolproof)
1) Using the “psl” (Public Suffix List) package
The
pslmodule knows about multi-level TLDs (e.g. “.co.uk”).npm install pslconst psl = require('psl'); function extractDomain(str) { // Find anything that looks like a hostname (with or without protocol) // then parse out the registered domain. const hostMatch = str.match( /([a-z0-9\-]+\.)+[a-z]{2,}(?=[\/:\s]|$)/gi ); if (!hostMatch) return null; // We might get multiple hosts in the string; pick the first const host = hostMatch[0]; // psl.get(...) returns e.g. "example.co.uk", or null if it’s an IP or invalid return psl.get(host); } // Examples console.log(extractDomain("Visit https://sub.foo.example.co.uk/path")); // → "example.co.uk" console.log(extractDomain("Check example.com?x=1")); // → "example.com" console.log(extractDomain("no-domain-here")); // → nullPros: correctly handles
foo.bar.example.co.uk→example.co.uk
Cons: adds a small dependency (~200 KB unminified)
2) Quick & Dirty with Regex + URL
If you just need the last two labels (e.g.
"example.com"from anything), you can:function extractDomainQuick(str) { // 1) Beef it up to a valid URL so URL parser will accept it const guessed = str.match(/https?:\/\//i) ? str : 'http://' + str.trim(); let hostname; try { hostname = new URL(guessed).hostname; } catch { // no valid host found return null; } // 2) Split on dots, take the last two parts const parts = hostname.split('.'); if (parts.length < 2) return null; const tld = parts.pop(); const dom = parts.pop(); return `${dom}.${tld}`; } // Examples console.log(extractDomainQuick("random text sub.foo.example.com/page")); // → "example.com" console.log(extractDomainQuick("sub.fancy.site.co.uk")); // → "co.uk" 👉 WRONG! you probably wanted "site.co.uk"Pros: zero dependencies, easy to drop in
Cons: won’t handle multi-level TLDs correctly (e.g..co.uk,.gov.au), and may pick up junk if your string contains weird dots
Which to choose?
- If you care about real registered domains (including .co.uk, .org.au, etc.), go with psl (or
tldts/tldjs– same idea). - If you just need a quick hack for “always take the last two labels,” use the regex+URL trick.
Let me know if you need examples for browser-only usage or a pure-regex-only version! 😊
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.