Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript正则表达式:如何从字符串中提取某些匹配项?_Javascript_Regex - Fatal编程技术网

JavaScript正则表达式:如何从字符串中提取某些匹配项?

JavaScript正则表达式:如何从字符串中提取某些匹配项?,javascript,regex,Javascript,Regex,HTML: 他已经岁了。他是一名教师。 JS: String.prototype.template=函数(数据){ var tags=this.match(/\/); 控制台日志(标签); }; document.getElementById('tpl-person').innerHTML.template({ 名称:“TK”, 年龄:25岁, 职业:“网络开发者” }); 上面的控制台日志是: 输出为: ["<%= name %>", " name ", index: 3,

HTML:


他已经岁了。他是一名教师。
JS:

String.prototype.template=函数(数据){
var tags=this.match(/\/);
控制台日志(标签);
};
document.getElementById('tpl-person').innerHTML.template({
名称:“TK”,
年龄:25岁,
职业:“网络开发者”
});
上面的控制台日志是:

输出为:

["<%= name %>", " name ", index: 3, input: "↵  <%= name %> is <%= age %> years old. He works as a <%= occupation %>."]
[“”,“名称”,索引:3,输入:↵   岁。他是一名律师
我需要它只是:

["<%= name %>", "<%= age %>", "<%= occupation %>"]
[“”,“”,“”]

如何获取此信息?

使用
g
修饰符:
/g

这将为您提供一个匹配数组,而不是第一个匹配及其子模式

编辑:也就是说,您可能需要替换:

return this.replace(/<%=\s*(.+?)\s*%>/g,function(_,key) {
    return data[key] || "##"+key+"##";
    // that || and the bit after it offer a fallback so you can see failed tags
});
返回这个.replace(//g,函数(\ux,键){
返回数据[键]| |“##”+键+“##”;
//该| | |及其后的位提供了一个回退,以便您可以看到失败的标记
});

使用
g
修饰符:
/g

这将为您提供一个匹配数组,而不是第一个匹配及其子模式

编辑:也就是说,您可能需要替换:

return this.replace(/<%=\s*(.+?)\s*%>/g,function(_,key) {
    return data[key] || "##"+key+"##";
    // that || and the bit after it offer a fallback so you can see failed tags
});
返回这个.replace(//g,函数(\ux,键){
返回数据[键]| |“##”+键+“##”;
//该| | |及其后的位提供了一个回退,以便您可以看到失败的标记
});

使用
g
修饰符:
/g

这将为您提供一个匹配数组,而不是第一个匹配及其子模式

编辑:也就是说,您可能需要替换:

return this.replace(/<%=\s*(.+?)\s*%>/g,function(_,key) {
    return data[key] || "##"+key+"##";
    // that || and the bit after it offer a fallback so you can see failed tags
});
返回这个.replace(//g,函数(\ux,键){
返回数据[键]| |“##”+键+“##”;
//该| | |及其后的位提供了一个回退,以便您可以看到失败的标记
});

使用
g
修饰符:
/g

这将为您提供一个匹配数组,而不是第一个匹配及其子模式

编辑:也就是说,您可能需要替换:

return this.replace(/<%=\s*(.+?)\s*%>/g,function(_,key) {
    return data[key] || "##"+key+"##";
    // that || and the bit after it offer a fallback so you can see failed tags
});
返回这个.replace(//g,函数(\ux,键){
返回数据[键]| |“##”+键+“##”;
//该| | |及其后的位提供了一个回退,以便您可以看到失败的标记
});