Lang is a lightweight library for handling automatic text translations with customizable markers. It works both in Node.js and browser environments.
-
Error Handling Update:
Previous behavior of throwing an error when the number of translations did not match the number of languages has been replaced. Now, missing translations are filled with empty strings (''
). -
New Methods Added:
-
add(items)
: Adds new key-value pairs to the existing dictionary. For each key, translations are added for the existing languages, with missing translations filled as empty strings. -
merge(data)
: Creates a newLang
instance by merging the current instance with the provided data. Combines dictionaries, with priority given to the current instance's data when conflicts arise.
-
npm install lang-library
In Node.js:
const Lang = require('lang-library');
In the browser:
<script src="/node_modules/als-lang/lang.js"></script>
<!-- or Minified: -->
<script src="/node_modules/als-lang/lang.min.js"></script>
const data = {
dictionary: {
'Hello, world!': ['Привет, мир!', 'Hola, mundo!'],
'How are you?': ['Как дела?', '¿Cómo estás?'],
},
langs: ['ru', 'es'],
};
const translator = new Lang(data, 'ru'); // Default language is Russian
-
dictionary
: An object where keys are original phrases, and values are arrays of translations for each language. -
langs
: An array of language codes (e.g.,['ru', 'es']
). -
defaultLang
: (Optional) The fallback language code when a translation is unavailable. Defaults to'en'
.
Returns a function that takes text and translates it into the specified language if a translation exists. If no translation is available, it returns the original text.
-
lang
: The target language code.
const translator = new Lang(data, 'ru');
const translate = translator.dictionaryFn('ru');
console.log(translate('Hello, world!'));
// Output: Привет, мир!
console.log(translate('Unknown phrase'));
// Output: Unknown phrase
Replaces all occurrences of text wrapped in the defined markers (~...~
) with the corresponding translation. Internally uses the dictionaryFn
method to fetch translations.
-
text
: The string containing text wrapped in markers (e.g.,~Hello, world!~
). -
lang
: The target language code for the translation.
const text = 'Welcome! ~Hello, world!~ ~How are you?~';
console.log(translator.replace(text, 'ru'));
// Output: Welcome! Привет, мир! Как дела?
console.log(translator.replace(text, 'es'));
// Output: Welcome! Hola, mundo! ¿Cómo estás?
If the translation for the specified language is not available, the original text is returned:
console.log(translator.replace(text, 'fr'));
// Output: Welcome! Hello, world! How are you?
By default, ~
is used as the start and end marker. You can change it globally:
Lang._start = '{{';
Lang._end = '}}';
const customTranslator = new Lang(data, 'ru');
const text = 'Welcome! {{Hello, world!}} {{How are you?}}';
console.log(customTranslator.replace(text, 'ru'));
// Output: Welcome! Привет, мир! Как дела?
Note: Markers must be the same for all instances.
-
Invalid Language Array:
- If
langs
is not an array, an error will be thrown:
const invalidData = { dictionary: {}, langs: 'ru, es' }; new Lang(invalidData); // Error: Langs must be an array
- If
const data = {
dictionary: {
'Welcome!': ['Добро пожаловать!', '¡Bienvenidos!'],
},
langs: ['ru', 'es'],
};
const translator = new Lang(data, 'ru');
console.log(translator.replace('~Welcome!~', 'ru'));
// Output: Добро пожаловать!
const translator = new Lang(data, 'es'); // Default is Spanish
console.log(translator.replace('~Welcome!~', 'fr'));
// Output: ¡Bienvenidos!
const emptyData = { dictionary: {}, langs: ['ru', 'es'] };
const translator = new Lang(emptyData);
console.log(translator.replace('~Unknown phrase~', 'ru'));
// Output: Unknown phrase
The add
method allows you to dynamically add new translations to the existing Lang
instance. If a translation for a specific language is missing, it is automatically filled with an empty string (''
).
-
items
: An object where keys are original phrases, and values are arrays of translations for each language.
const lang = new Lang({
langs: ['en', 'es'],
dictionary: { hello: ['Hello', 'Hola'] },
});
lang.add({
goodbye: ['Goodbye', 'Adiós'],
world: ['World'], // Spanish translation missing
});
console.log(lang.langs);
// Output:
// {
// en: { hello: 'Hello', goodbye: 'Goodbye', world: 'World' },
// es: { hello: 'Hola', goodbye: 'Adiós', world: '' },
// }
The merge
method creates a new Lang
instance by combining the current instance's data with the provided data. The method ensures that translations from the current instance take precedence in case of conflicts.
-
data
: An object withlangs
(array) anddictionary
(object) properties to merge into the current instance or another Lang instance.
const lang1 = new Lang({
langs: ['en', 'es'],
dictionary: { hello: ['Hello', 'Hola'] },
});
const mergedLang = lang1.merge({
langs: ['en', 'fr'], // Adding French
dictionary: { goodbye: ['Goodbye', 'Au revoir'], hello: ['Hi', 'Salut'] },
});
// Or
const mergedLang = lang1.merge(new Lang({
langs: ['en', 'fr'], // Adding French
dictionary: { goodbye: ['Goodbye', 'Au revoir'], hello: ['Hi', 'Salut'] },
}));
console.log(mergedLang.langs);
// Output:
// {
// en: { hello: 'Hello', goodbye: 'Goodbye' },
// es: { hello: 'Hola', goodbye: '' },
// fr: { hello: 'Salut', goodbye: 'Au revoir' },
// }
- The library works seamlessly in both Node.js and browser environments.
- Translations should be provided as arrays with values matching the order of
langs
. - Custom markers (
start
andend
) must be globally consistent for all instances. -
- The
add
method allows dynamic updates to the dictionary, filling missing translations with empty strings (''
).
- The
- The
merge
method creates a newLang
instance by combining data from two sources, with the current instance's data taking precedence.