2016-06-24 74 views
0

var string = "https://example.com/app/something"; var string = "example.com/app/something"; new URL(string.origin) 如何從字符串獲取域名?

如果string的協議一切正常,如果沒有。有錯誤無法構建「網址」:無效的網址(...)

如何在不使用正則表達式的情況下獲取根域?

+0

'string.origin'是'undefined'。你的意思是'location.origin'?如果你這樣做,爲什麼你會*沒有協議? –

+0

@ p.s.w.g我在想同樣的事情,但我相信OP沒有從'window.location'對象獲取URL。如果是這種情況,我不知道如何在不使用正則表達式的情況下獲取URL原點。 – Nitsew

+0

'new URL('http://example.com/app/something')'返回對象如果字符串有http或https – JDO

回答

0

的問題仍然是一個有點不清楚,我不完全知道你是如何得到這個字符串,但只是爲了討論的方便,這裏有一個快速的解決方案:

function getHostname(str) 
 
{ 
 
    str = (/^\w+:\/\//.test(str) ? "" : "http://") + str 
 
    return new URL(str).hostname; 
 
} 
 

 
console.log(getHostname("https://example.com/app/something")); 
 
console.log(getHostname("example.com/app/something"));

是的,從技術上講,這在技術上確實使用正則表達式來檢查協議是否存在,但它使用URL類實際解析主機名。

+0

這是比我的更好的解決方案。我甚至沒有想過使用'URL.hostname',做得好! – TheZanke

-1

如果我正確理解你的問題,你想檢查URL是否包含http或https協議。這可以通過JavaScript中內置的字符串函數輕鬆完成,如下所示。

var string = window.location; 
if (string.includes('http') || string.includes('https')) 
{ 
    //Do your logic here 
} 

更新:或者,您可以使用下面顯示的子字符串功能。

var string = window.location; 
if (string.indexOf('http') == 0) 
{ 
    //Do your logic here 
} 

請注意,這也將驗證http是否在字符串的開頭,而不是隻是在不知不覺中拋出。

+0

包括很好,​​但請記住它沒有很好的支持:https:// developer .mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Browser_compatibility – Nitsew

+0

好的!我用更好的版本更新了評論。 – cmw2379

+0

如果字符串類似於「example.com/http」','includes'也不起作用。 'indexOf'是一個好得多的解決方案,但它不起作用,字符串就像''http.example.com/app「'(這是不常見的情況)。 –

0

正則表達式例如:

var example1 = "www.example1.com/test/path"; 
 
var example2 = "https://example2.com/test/path"; 
 
var example3 = "http://subdomain.example3.com/test/path"; 
 

 
function getDomain(str) { 
 
    var matches = str.match(/^(?:https?:\/\/)?((?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6})/); 
 
    if (!matches || matches.length < 2) return ''; 
 
    return matches[1]; 
 
} 
 

 
console.log(getDomain(example1)); 
 
console.log(getDomain(example2)); 
 
console.log(getDomain(example3));

參考文獻: