2012-01-09 36 views
1

我需要得到的語言,用戶使用基於document.location檢查/ EN /或/ ES /在document.location

URL是類型:

domain.com/en/blabla.html 
domain.com/es/blabla.html 
domain.com/it/blabla.html 

所以我想是這樣的:

function getLan(){ 
    var idioma = document.location; 
    var idiomaTmp = idioma.split("/"); 
    return = idiomaTmp[1]; 
} 

但(我不明白,但)我在螢火得到這個錯誤

idioma.split is not a function 
[Detener en este error] var idiomaTmp = idioma.split("/"); 

有什麼想法爲什麼?或者更好的解決方案?

回答

3

document.location是一個對象。雖然是有自定義的toString方法,所以alert(document.location)顯示實際的url,它本身不是一個字符串,並且String方法不起作用。你想要的是使用字符串方法之前,這個對象轉換爲字符串:

document.location.toString().split(...) etc 

對於一個更好的解決方案,嘗試正則表達式:

var m = document.location.toString().match(/\/([a-z][a-z])\//) 
language = m ? m[1] : "default"; 
+0

重要的語言也可以是'en_US'或類似的東西,所以使用這個正則表達式:'/ \ /([az] {2}(_ [AZ] {2})?)\ // ' – noob 2012-01-09 09:26:24

2

你想location.hrefdocument.location

-2

使用document.location.href.split( '/'),而不是document.location.href.split( 「/」),那麼如果你需要使用字符串(,)

+1

document.location.split不是函數 – 2012-01-09 09:12:23

+0

文件。 location.href – ONYX 2012-01-09 09:12:53

+0

不要使用雙引號 – ONYX 2012-01-09 09:13:24

0

在代碼中找你第一個錯誤是,在return後不需要=

第二個錯誤是document.location將返回一個對象的詳細信息,而不是一個字符串。

其實你想這(將只返回路徑)

window.location.pathname // example: /en/ 

所以找你函數看起來就像這樣:

function getLang() { 
    return window.location.pathname.split("/")[1]; 
} 
相關問題