'use strict'; let messages = { "Hello, {0}!": "Привет, {0}!" }; function i18n(strings, ...values) { let pattern = ""; for(let i=0; i<values.length; i++) { pattern += strings[i] + '{' + i + '}'; } pattern += strings[strings.length-1]; let translated = messages[pattern]; return translated.replace(/\{(\d)\}/g, (s, num) => values[num]); } let name = "Вася"; alert( i18n`Hello, ${name}!` ); |
1 answer
return translated.replace(/\{(\d)\}/g, (s, num) => values[num]);
Maybe I'm wrong, but the behavior here is -
translatedis assigned index value, i.e. in this case, will returnПривет , {0}RegExppulls out just such a sequence{цифра}from themessagesstring (which is thentranslated). Those. for exampleПривет {0} -> {0}- Then it replaces it with the value calculated in the arrow function, i.e. if
valueshas 1 element (i.e. index0), the function returns the value ofvalues[0](thevaluesin this case will be 'Vasya') and substitute{0}fortranslated. - As a result, instead of the one who came to the entrance to the translated
Привет, {0}, there will beПривет, Вася.
Those. RegExp itself simply returns only entries of numbers in the search string, and replace replaces it with the value from the calculated function.
|
translated- Igor