0

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..

2
  • Have you tried anything? Something with .map() or just a for loop maybe? Commented Feb 26, 2021 at 10:20
  • Is "English" en-us or en-uk? Which dialect of Chinese is "Chinese" exactly? If you're expecting some magic library or API that does this conversion for you, you'd probably fail in some way or another when it comes to these questions. You'll kinda need to define this mapping yourself. Commented Feb 26, 2021 at 10:22

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.