There is a string like:

NAME=ИМЯ,SURNAME=ФАМИЛИЯ,PATRONYMIC=ОТЧЕСТВО, IIN=123456789012, COUNTRY=СТРАНА,CITY=ГОРОД, EMAIL=ИМЯ@MAIL.RU 

You need to search for the word COUNTRY or ( NAME, SURNAME, CITY, EMAIL ). If there is such a word, then immediately cut this word to a comma, that is, IIN=123456789012

How can you make it easier on one or not more than two lines?

    3 answers 3

     var string = "NAME=ИМЯ,SURNAME=ФАМИЛИЯ,PATRONYMIC=ОТЧЕСТВО, IIN=123456789012, COUNTRY=СТРАНА,CITY=ГОРОД, EMAIL=ИМЯ@MAIL.RU"; // вариант через match console.log(string.match(/NAME=(.*?),/m)[1]); console.log(string.match(/SURNAME=(.*?),/m)[1]); console.log(string.match(/PATRONYMIC=(.*?),/m)[1]); console.log(string.match(/IIN=(.*?),/m)[1]); console.log(string.match(/COUNTRY=(.*?),/m)[1]); console.log(string.match(/CITY=(.*?),/m)[1]); console.log(string.match(/EMAIL=(.*),?/m)[1]); // вариант через split var array = string.split(","); array.forEach(function(value) { console.log(value.split("=")[1].trim()); // в "value.split("=")[0].trim()" название ключа }); 

    If you need to parse with multiple lines, use split("\n")

       let str = 'NAME=ИМЯ,SURNAME=ФАМИЛИЯ,PATRONYMIC=ОТЧЕСТВО, IIN=123456789012, COUNTRY=СТРАНА, CITY=ГОРОД, EMAIL=ИМЯ@MAIL.RU'; let findStr = 'COUNTRY'; let result = str.split(','); result.forEach(element => { if (element.trim().indexOf(findStr) == 0) { result = element; } }); console.log(result); 

      • let which team? js gives an error - Tolembek
      • "let" is a variable type as well as "var", the current is slightly different). ES2015 learn.javascript.ru/let-const Can be replaced by "var". - mr_White
       var t = 'NAME=ИМЯ,SURNAME=ФАМИЛИЯ,PATRONYMIC=ОТЧЕСТВО, IIN=123456789012, COUNTRY=СТРАНА, CITY=ГОРОД, EMAIL=ИМЯ@MAIL.RU'; const result = {}; t.split(',').map(v => { var T = v.trim().split('='); result[T[0]] = T[1]; }); 

      as a result there will be such an object

       result = { CITY: "ГОРОД" COUNTRY: "СТРАНА" EMAIL: "ИМЯ@MAIL.RU" IIN: "123456789012" NAME: "ИМЯ" PATRONYMIC: "ОТЧЕСТВО" SURNAME: "ФАМИЛИЯ" } 

      in order to have something there we should

       if (result.EMAIL) { // // делаем что то } 
      • Your code is excellent, but how can I find out if the object has EMAIL or not? How does it let the object through the loop and find out whether the IIN is or not? - Tolembek
      • updated the answer 344 - Sasuke
      • Hello! Sanitary your code is great for me, thanks. I did not know that this is possible))) if (result.EMAIL) {// // do something} - Tolembek