Как найти имя переменной тегов EJS из строки? - PullRequest
0 голосов
/ 05 ноября 2019

У меня EJS String, и я пытаюсь получить EJS имен переменных тегов в объекте: {name: 1, car: 1}, потому что мне нужно проецировать только те значения из базы данных, которые присутствуют встрока.

Пример:

let str = "His name is <%= name %> and he has <%= car[0].color %> car. <%= name %> is working in XYZ";
    str = str.split(' ');

    let project = {};
    str.forEach((text, index) =>{
        if(text === '<%='){
            project[str[index + 1].split('[')[0]] = 1;
        }
    });

    console.log(project) // {name: 1, car: 1}

Есть ли лучший способ добиться того же или с помощью RegEx.

1 Ответ

1 голос
/ 05 ноября 2019

Пытался сделать это с регулярным выражением

var pattern = "<%=\s[a-zA-Z]+"; // will also find the '<%= ' at the beginning, will be cut out later
var str = "His name is <%= name %> and he has <%= car[0].color %> car. <%= name %> is working in XYZ";
var found = str.match(pattern); // get all matches

let project = {};
found.forEach((text, index) =>{
    found[index] = found[index].substring(4); // to cut out '<%= '
    project[found[index]] = 1; // add it to the array
});

console.log(project);
...