如何使用jQuery提取域名中的.com/.it/.de等后缀?
Hey there! I’ve got a couple of straightforward, reliable ways to pull those domain suffixes from your URLs using jQuery (under the hood, we’ll use plain JavaScript since jQuery just wraps it—no extra fluff needed). Let’s break this down:
Method 1: Use the Native URL Object (Recommended)
This is the cleanest, most browser-friendly approach for modern environments. The URL object handles all the heavy lifting of parsing URLs, so you don’t have to mess with messy regex for basic cases.
Here’s how it works:
// Example URL to test const targetUrl = "https://example.de/Controller/Index"; // Step 1: Create a URL object from your string const urlObj = new URL(targetUrl); // Step 2: Grab the hostname (e.g., "example.de") const hostname = urlObj.hostname; // Step 3: Split the hostname and grab the last segment (the suffix) const suffix = `.${hostname.split('.').slice(-1)[0]}`; // Results in ".de" console.log(suffix); // Outputs: .de
Why this works:
- The
URLobject natively parses even tricky URLs (like those with subdomains or query params) without breaking a sweat. - If you have a URL like
https://sub.example.co.uk/Page, this will grab.uk—if you need to handle multi-part suffixes like.co.uk, you’d need to expand this with a public suffix list, but that’s a more advanced use case!
Method 2: Regular Expressions (For Older Browsers or Custom Matching)
If you need to support older browsers that don’t have the URL object, or want more control over the matching pattern, a regex works great.
Here’s a simple regex to target the suffix:
const targetUrl = "https://example.it/Controller/Index"; // Match a dot followed by 2-3 letters, ending before a slash or the end of the string const suffixMatch = targetUrl.match(/\.([a-z]{2,3})(?:\/|$)/i); if (suffixMatch) { const suffix = `.${suffixMatch[1]}`; // Results in ".it" console.log(suffix); } else { console.log("No valid domain suffix found"); }
How the regex works:
\.: Matches the literal dot before the suffix([a-z]{2,3}): Captures 2-3 alphabetical characters (covers most common suffixes like .com, .de, .it)(?:\/|$): Looks for a slash or the end of the string to ensure we don’t match extra charactersi: Makes the match case-insensitive (so.COMor.Dework too)
Using This with jQuery (For Page Links)
If you’re extracting suffixes from links on your page, here’s how to wrap this logic in jQuery:
// Loop through all links on the page $('a').each(function() { const linkUrl = $(this).attr('href'); if (linkUrl) { try { // Handle relative URLs by using the page's base URL const fullUrl = new URL(linkUrl, window.location.href); const hostnameParts = fullUrl.hostname.split('.'); const suffix = `.${hostnameParts.slice(-1)[0]}`; console.log(`Suffix for ${linkUrl}: ${suffix}`); } catch (err) { console.error(`Skipping invalid URL: ${linkUrl}`); } } });
Quick Notes:
- Always wrap
URLcreation in atry/catchblock to handle invalid URLs gracefully. - For relative URLs, pass
window.location.hrefas the second argument to theURLconstructor to resolve it to a full URL.
内容的提问来源于stack exchange,提问作者User987

