-
Notifications
You must be signed in to change notification settings - Fork 1
/
parseText.js
48 lines (35 loc) · 975 Bytes
/
parseText.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* 类似于Vue中的模板解析
* */
function parseText (text) {
const tagRE = /\{\{((?:.|\n)+?)\}\}/g
if (!tagRE.test(text)) {
return;
}
const tokens = [];
let lastIndex = tagRE.lastIndex = 0;
let match, index;
while (( match = tagRE.exec(text))){
index = match.index;
if(index > lastIndex) {
tokens.push(JSON.stringify(text.slice(lastIndex, index)));
}
tokens.push(`_s(${match[1].trim()})`);
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
tokens.push(JSON.stringify(text.slice(lastIndex)));
}
return tokens.join('+');
}
function _s(val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val);
}
function getStr(obj, tpl) {
let strFunc = new Function('obj', 'with(obj){str = ' + tpl + '} return str;');
return strFunc(obj);
}