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?
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?
Share Improve this question edited Aug 12, 2020 at 12:22 KristalkillPlay asked Aug 12, 2020 at 12:06 KristalkillPlayKristalkillPlay 2123 silver badges10 bronze badges 3- Are you asking how to escape backticks in JSON? – jannis Commented Aug 12, 2020 at 12:31
- Yes,i am asking how to escape backticks in JSON – KristalkillPlay Commented Aug 12, 2020 at 12:32
- JSON allows unescaped backticks. – jannis Commented Aug 12, 2020 at 12:38
1 Answer
Reset to default 9You 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.