-1

Please i ask for your help. I found some ideas online and they managed to create a sort of personalized message based on the visitor's language, however, the script fails if the country code is added in addition to the language code.

My intent is to far show a personalized message based on the language code "tag lang" followed by a country code to differentiate some messages.

For example use lang = "en-US" for users in English who view the page from the United States and use lang = "en-GB" with the relevant personalized message for users viewing the web page from Great Britain.

This is the code used:

var known = {
    en: true,
    it: true,
    en-US: true,
};
var lang = ((navigator.languages && navigator.languages[0]) && navigator.language || navigator.userLanguage || 'en').substr(0, 2);
if(!known[lang])
    lang = 'en';
$('div.wrapper[lang=' + lang + ']').show();
$('div.wrapper[lang!=' + lang + ']').hide(); 
<div lang="en" class="wrapper">
    <h1>English</h1>
    <p>Here is some English content.</p>
</div>
<div lang="it" class="wrapper">
    <h1>Italiano</h1>
    <p>Ecco alcuni contenuti in Italiano.</p>
</div>
<div lang="en-US" class="wrapper">
    <h1>English United States</h1>
    <p>Here are some English content from the United States</p>
</div>

Can you help me please?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • You faced an interalization problem. There are many solutions exists, you can have a look to this anwer, it may be helpful: https://stackoverflow.com/a/3084798/1330261 – Dmitriy Mar 30 '20 at 14:54

1 Answers1

0

Thank you very much for the tip!

I tried to modify the code by inserting the tag (eg lang = "en-US"), but it doesn't display the correct content.

var known = {
    en: true,
    'it-IT': true,
    'en-US': true,
    'en-GB': true,
};
var lang = ((navigator.languages && navigator.languages[0]) && navigator.language || navigator.userLanguage || 'it-IT').substr(0, 2);

console.log('LANG: ' + lang)

if(!known[lang])
    lang = 'it-IT';
$('div.wrapper[lang=' + lang + ']').show();
$('div.wrapper[lang!=' + lang + ']').hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div lang="en-US" class="wrapper">
    <h1>English US</h1>
    <p>Here is some English content.</p>
</div>

<div lang="en-GB" class="wrapper">
    <h1>English GB</h1>
    <p>Here are some English content from the United States</p>
</div>

<div lang="it-IT" class="wrapper">
    <h1>Italiano</h1>
    <p>Ecco alcuni contenuti in Italiano.</p>
</div>

What else am I doing wrong?

palaѕн
  • 72,112
  • 17
  • 116
  • 136