I decided to localize the site here, but some points have to do on js.

The question is: You need a regular expression with which you can replace variables in a variable containing an html block with the corresponding variables of the language.

There is a variable containing html code to be displayed on the screen. Here is an example.

<div class="width-250"> <button type="button" class="btn btn-sm btn-primary">{ev_textone}</button> <button type="button" class="btn btn-sm btn-primary">{ev_texttwo}</button> <button type="button" class="btn btn-sm btn-primary">{ev_other}</button> </div> 

And as you can see in the code, there are language variables that are in braces. There is a language file that is loaded on the page initially. The task is to change curly brackets with variables to the corresponding words or phrases from the language array.

 var lang = { ev_textone: "Это поле не должно быть пустым", ev_other: "Длинна этого поля должна быть от 5 до 30 символов", ev_texttwo: "Максимальная длинна этого поля 255 символов", ev_dateright: "Введите дату и время в формате ДД-ММ-ГГГГ ЧЧ:ММ" … } 

The data is loaded dynamically .. after opening the page, so I decided to deduce the required language in this way. Help with a regular expression or code that will help me with this.

  • Where is your solution? - user207618
  • for (var word in lang) {m [key] = m [key] .split ('{' + word + '}'). join (lang [word]); } seems to me a very difficult option, because I have a large language file. - Ivan Savin
  • Not on the topic, of course, but the word "length" is written with one "n". :) - labris

1 answer 1

 let lang = { ev_textone: "Это поле не должно быть пустым", ev_other: "Длинна этого поля должна быть от 5 до 30 символов", ev_texttwo: "Максимальная длинна этого поля 255 символов", ev_dateright: "Введите дату и время в формате ДД-ММ-ГГГГ ЧЧ:ММ" }, template = `<div class="width-250"> <button type="button" class="btn btn-sm btn-primary">{ev_textone}</button> <button type="button" class="btn btn-sm btn-primary">{ev_texttwo}</button> <button type="button" class="btn btn-sm btn-primary">{ev_other}</button> </div>`; // Ищем "a-z_"-символы между фигурных скобок // Если найденная фраза есть в словаре - возвращаем значение, иначе возвращаем найденное document.body.innerHTML = template.replace(/{\s*([a-z_]+)\s*}/ig, (_, key) => key in lang ? lang[key] : _); 

  • Thank you, this is exactly what I wanted. - Ivan Savin
  • @IvanSavin, please. Thanks here are expressed in reputation and, if decided, by accepting an answer (tick to the left of the answer). - user207618
  • Be sure to put. I am a new user ... - Ivan Savin