'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}!` ); 
  • which one? in code two lines with translated - Igor
  • An interesting implementation of localization. - Qwertiy
  • @ A.Gusev, What is the joke of asking a question to a question ?! If you do not know yourself, then do not ask this! And you know - write! - HamSter

1 answer 1

return translated.replace(/\{(\d)\}/g, (s, num) => values[num]);

Maybe I'm wrong, but the behavior here is -

  1. translated is assigned index value, i.e. in this case, will return Привет , {0}
  2. RegExp pulls out just such a sequence {цифра} from the messages string (which is then translated ). Those. for example Привет {0} -> {0}
  3. Then it replaces it with the value calculated in the arrow function, i.e. if values has 1 element (i.e. index 0 ), the function returns the value of values[0] (the values in this case will be 'Vasya') and substitute {0} for translated .
  4. 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.