For the reverse of Michal Bryxí's answer, using Intl.DisplayNames to get the ISO 639-1 code from the language name (e.g. English
➜ en
):
function generateLangMap () {
const langNames = new Intl.DisplayNames(['en'], {type: 'language'})
const langMap = {}
for (let i = 0; i < 26; i++) {
for (let j = 0; j < 26; j++) {
let code = String.fromCharCode(97 + i) + String.fromCharCode(97 + j)
let name = langNames.of(code)
if (name !== code) {
langMap[name] = code
}
}
}
const langMap2 = {
// Avoid using deprecated codes:
'Akan': 'ak',
'Hebrew': 'he',
'Indonesian': 'id',
'Javanese': 'jv',
'Romanian': 'ro',
'Yiddish': 'yi',
// Optional extras:
'Tagalog': 'tl',
}
return { ...langMap, ...langMap2 }
}
// Usage:
const langMap = generateLangMap()
console.log(langMap['English']) // 'en'
console.log(langMap['Chinese']) // 'zh'
console.log(langMap['Spanish']) // 'es'