skip to Main Content
let language = navigator.language;

switch (language) {
    case es :
        document.getElementById("demo").innerText =  "Hola ";
        break;
    case en :
        document.getElementById("demo").innerText =  "Hello ";          
}

Am not receiving anything back.
I would appreciate if someone knows why it isn’t working

2

Answers


  1. I am assuming your html looks like this:

    <body>
        <h1 id="demo">Hello World</h1>
    </body>
    <script src="app.js"></script>
    

    and my js file:

    const language = navigator.language;
    switch (language) {
                    case 'es' :
                    document.getElementById("demo").innerText =  "Hola ";
                    break;
                    case 'en' :
                    document.getElementById("demo").innerText =  "Hello ";
                    
                    }
    

    You need to add quotes around you language switch case ‘es’ not es … Because navigator.language returns a string and if you don’t use quotes javascript is going to be looking for a variable or a function call.

    when I made those modifications your code worked just fine.

    Login or Signup to reply.
  2. You will need to wrap quotes around the possible values and you need to parse the language value to look like the values in your switch case:

    let language = navigator.language;
    let dashIndex = language.indexOf('-');
    if (dashIndex >= 0) {
        language = language.substring(0, dashIndex);
    }
    
    switch (language) {
                    case 'es' :
                    document.getElementById("demo").innerText =  "Hola ";
                    break;
                    case 'en' :
                    document.getElementById("demo").innerText =  "Hello ";
                    
                    }
    <h1 id="demo"></h1>

    Note that instead of case 'en' : you could use default : which would use the English language as a default even if the language has a value that your code did not expect.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search