I have been working on an application where i need to redirect user to the selected pages that are translated in the respective locale. I have been getting a list of languages from the backend. I need to convert the languages in the language code. For example:
var languageName = ['English', 'Japnese', 'Chinese'];
Need to convert them to
['en-us','ja-jp','zh-cn'];
How can i convert the language name to language locale or country code..
A simple solution with a mapping object:
const mappings = { 'English': 'en-us', 'Japanese': 'ja-jp', 'Chinese': 'zh-cn' }; const languageName = ['English', 'Japanese', 'Chinese']; const output = languageName.map(lang => mappings[lang]); console.log(output);
You can use an object as a mapping and then use a languege you want to get a locale for as a key:
const mapping = {
'English' : 'en-us',
'Japanese' : 'ja-jp',
...
};
const desiredLanguage='English';
console.log(mapping[desiredLanguage]) // outputs "en-us"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.