如何从字符串中找到EJS标签变量名?

我有EJS字符串,并且我试图在对象{name: 1,car: 1}中获得 EJS 标签变量名,因为我只需要从数据库中投影那些存在的值在字符串中。

示例:

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。

heroliyimin 回答:如何从字符串中找到EJS标签变量名?

试图使用正则表达式

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);
本文链接:https://www.f2er.com/3159824.html

大家都在问