I have en.json and ru.json files, I use variables by type there:
levelupmessage: "Congratulations on the new $ {level}"
because in json you cannot put `` what needs to be done so that there is not just a string?
You need to create a module that loads all messages from en.json and ru.json and saves them in an object.
Then, create a function that finds the specified string inside your object. This function also replaces %VAR% with a parameter you pass to that function.
Take a look at this example:
let strings = {
en: {
// I prefer % for variables
levelUp: "Congratulations on leveling up: %VAR%"
},
ru: {
levelUp: "Поздравляем с новым уровнем: %VAR%"
}
};
// Function to get locales and replace variables
function getLocale(language, string, ...vars) {
let locale = strings[language][string];
let count = 0;
locale = locale.replace(/%VAR%/g, () => vars[count] !== null ? vars[count] : "%VAR%");
return locale;
}
getLocale("en", "levelUp", "10"); // Congratulations on leveling up: 10
getLocale("ru", "levelUp", "10"); // Поздравляем с новым уровнем: 10
That's how many popular Discord bots handle internationalization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With