masgar
masgar

Reputation: 1873

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) + 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

Upvotes: 1

Views: 7360

Answers (3)

Joe
Joe

Reputation: 82654

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;

Upvotes: 0

DoctorMick
DoctorMick

Reputation: 6793

Try this...

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

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76900

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/)

Upvotes: 0

Related Questions