簡體   English   中英

僅來自“sub.domain.com” JS 的正則表達式“域”

[英]Regex Only "domain" from "sub.domain.com" JS

我使用此規則來獲取唯一的主機名,但它不適用於超過 2 個字符的子域。 else ifreturn hostname[1]時,我嘗試過,但if運行仍然是第一個,那應該是什么。 我願意接受正確的正則表達式或替代解決方案。

效勞於:

代碼

var match = url.match(/:\/\/(www[0-9]?\.|[a-zA-Z]\.)?(.[^/:]+)/i);
if (match != null && match.length > 2 && typeof match[2] === 'string' && match[2].length > 0) {
    var hostname = match[2].split(".");
    return hostname[0];
}
else {
    return null;
}

盡管它可以解決您的問題,但它不是必需的正則表達式解決方案。

 const list = ['www.google.com', 'en.store.com', 'google.com', 'www2.site.com', 'www.google.com.tr', 'https://www.google.com.tr', 'shop.store.com' ]; function getName(url) { const parts = url.split('.'); return parts[parts.length - (parts.length > 3? 3: 2 )]; } list.forEach((item) => { console.log(item,getName(item)); });

我發現這個類似的帖子在這里是同一個鏈接的鏈接

URL 格式: https://order-dev.companyname.com

有助於從上述 URL (?<=\/\/)(.*?)(?=\.)

通過在 TLD like.com 之前獲取文本來解決

/(\w|-)+(?=(\.(com|net|org|info|coop|int|co|ac|ie|co|ai|eu|ca|icu|top|xyz|tk|cn|ga|cf|nl|us|eu|de|hk|am|tv|bingo|blackfriday|gov|edu|mil|arpa|au|ru)(\.|\/|$)))/g

資源

我對僅使用正則表達式的更好和更有效的解決方案持開放態度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM