正则表达式快速解析微信订阅,模板消息的字段与值

微信后台发送过来的消息模板一般都是下面的格式:

字段1
字段2

如果我们需要定制化推送模板消息,需要自己解析:

下面是一个方法:支持解析模板字段与模板字段值,item.content是模板所在的字符串.可以根据需要,取值,和取字段。

解析模板消息字段正则表达式:

let c = /(.*)\{\{/.exec(item2);

解析字段对应的值正则表达式:

let v = /.*?\{\{(.*?)\}\}/.exec(item2);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

//解析模板
desTemplate(item){
if(item.content){
item.content = item.content.split('\n')
}else{return}
item.records = {}
item.content.map((item2) => {
// 匹配出模板字段
let c = /(.*)\{\{/.exec(item2);
try {
console.log(c[1]);
let v = /.*?\{\{(.*?)\}\}/.exec(item2);
/如果需要取字段对应的值xx.x
item.records[c[1]] = v[1]


} catch (e) {
}
})
return item
},