开发者

javascript substr window.location.href

this is a very beginner question but I don't know javascript, I only wants implement a snipplet I found googling around.

The original code is:


var langcodes=["it", "es"];
var langCode = navigator.language || navigator.systemLanguage;
var lang = langCode.toLowerCase(); 
lang = lang.substr(0,2); 
var dest = window.location.href; 
for (i=langcodes.length-1;i >= 0; i--){
    if (lang==langcodes[i]){
        dest = dest.substr(0,dest.lastIndexOf('.')) + '-' + lang.substr(0,2) +开发者_如何学Go dest.substr(dest.lastIndexOf('.'));
        window.location.replace ?window.location.replace(dest) :window.location=dest;
    }
}

if my browser language is it_IT, will replace

    http://www.mysite.com/test.html 

to

    http://www.mysite.com/test-it.html 

i'd like the new url was:

    http://www.mysite.com/it/test.html 

I tried several ways with no luck.

Any help is appreciated.

Max


Try this...

 dest = dest.substr(0,dest.lastIndexOf('/')) + '/' + lang.substr(0,2) + dest.substr(dest.lastIndexOf('/'));


You could do:

if (lang==langcodes[i]){
    dest = dest.substr(0,dest.lastIndexOf('/') +1) + lang.substr(0,2) + dest.substr(dest.lastIndexOf('/'));
    window.location.replace ?window.location.replace(dest) :window.location=dest;
}

ok, tested on www.google.it and it woked (output www.google.it/it/)


Try this:

var langcodes=["it", "es"];
var langCode = navigator.language || navigator.systemLanguage;
var lang = langCode.toLowerCase(); 
lang = lang.substr(0,2); 
var dest = window.location.href;

dest = dest.substr(0,dest.lastIndexOf('.')) + '-' + lang + dest.substr(dest.lastIndexOf('.'));
window.location = dest;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜