簡體   English   中英

如何從字符串中找到 EJS 標簽變量名?

[英]How to find EJS tags variable name from String?

我有EJS字符串,我試圖在 object: {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。

試圖用正則表達式來做

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM