-
Notifications
You must be signed in to change notification settings - Fork 0
/
template-string.js
85 lines (56 loc) · 1.34 KB
/
template-string.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//------
`string text`
`text line1
text line2`
`\`hi\``
//------
let name = 'Jim';
`hello ${name}`
//------
let a = 1,b = 2;
`${a} + ${b} = ${a+b}`
//------
let a = {b:1};
`${a.b}`
//------
function foo(){
return 'bar';
}
`foo ${foo()}`
//------
let a = `${b}`
let a = `${`b`}`
//---------
alert`1`
alert(1)
//--------
fn`Hello ${arg1}, do you know ${arg2}?`
fn(["Hello ", ", do you know ", "?"], arg1, arg2);
//-------
function upperExpr (template, ...expressions) {
return template.reduce((accumulator, part, i) => {
return accumulator + expressions[i - 1].toUpperCase() + part
})
}
var name = 'world'
var text = upperExpr`hello ${name}`
console.log(text)
// => 'hello WORLD'
//-------
var message =
SaferHTML`<p>${sender} has sent you a message.</p>`;
function SaferHTML(templateData) {
var s = templateData[0];
for (var i = 1; i < arguments.length; i++) {
var arg = String(arguments[i]);
// Escape special characters in the substitution.
s += arg.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
// Don't escape special characters in the template.
s += templateData[i];
}
return s;
}
//---------
i18n`Hello,${name}!`