拆解字符串和变量
let desc = 'something'
let desc2 = 'something'
function bar () {
return function foo (string, ...values) {
console.log(string) // 前后字符串
console.log(values) // 变量
// [ 'EveryThing is ', '! But you not ', '!' ]
// [ 'something', 'something' ]
}
}
bar()`EveryThing is ${desc}! But you not ${desc2}!`
function tag (strings, ...values) {
return strings.reduce(function (s, v, idx) {
// s 为变量前字符串
// v 为变量后字符串
// values[idx - 1]是字符串下面对应的变量的值,思路基本都是对该值进行各种润饰处理。
return s + (idx > 0 ? values[idx - 1] : '') + v
}, '')
}
// let text = tag`EveryThing is ${desc}!`
let text = tag`EveryThing is ${desc}! But you not ${desc2}!`
console.log(text)
应用
- 转美元
function dollabillsyall (strings, ...values) {
return strings.reduce(function (s, v, idx) {
if (idx > 0) {
if (typeof values[idx - 1] == 'number') {
s += `$${values[idx - 1].toFixed(2)}`
} else {
s += values[idx - 1]
}
}
return s + v
})
}
let amt1 = 11.11
let amt2 = amt1 * 1.01
let custorm = "hjj"
let msg = dollabillsyall`Thanks for your purchase, ${custorm}! Your product cost was ${amt1}, which with tax comes out to ${amt2}`
console.log(msg)
- 过滤html
function safeHtml (strings, ...values) {
return strings.reduce(function (s, v, idx) {
return s + String(values[idx - 1]).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, '>') + v
})
}
let content = '<script>alert(1)</script>'
let html = safeHtml`${content} is safe html`
console.log(html)
- 多语言转换
function il8nCh (strings, ...values) {
let langugeMap = new Map([
['red', '红'],
['blue', "蓝"],
['yellow', "黄"],
])
return strings.reduce((s, v, idx) => s + langugeMap.get(values[idx - 1]) + v)
}
function il8nFrench (strings, ...values) {
let langugeMap = new Map([
['red', 'Rouge'],
['blue', "Bleu"],
['yellow', "Jaune"],
])
return strings.reduce((s, v, idx) => s + langugeMap.get(values[idx - 1]) + v)
}
let blue = 'blue'
let yellow = 'yellow'
let red = 'red'
let sendMsg = il8nCh`按钮的颜色有${red},${yellow},${blue}`
let sendMsg2 = il8nFrench`Les couleurs des boutons sont:${red},${yellow},${blue}`
console.log(sendMsg)
console.log(sendMsg2)
String.raw
String.raw的应用,反向组装字符串。与模板字面量对应
将拆解的字符串和变量组合起来,逆向第一个例子。
// String.raw({raw: ['msg1', 'msg2', ..., '']}, var1, var2, ...)
console.log(String.raw({ raw: ['EveryThing is ', '! But you not ', ''] }, desc, desc2))
// 过滤html+raw
function safeHtmlraw (strings, ...values) {
// return strings.reduce(function (s, v, idx) {
// return s + String(values[idx - 1]).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, '>') + v
// })
// string 这个作为数组传人
// values 单独处理变量
values = values.map(item => {
item = String(item).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, '>')
return item
})
// 处理好变量后直接丢回去,思路清晰明了。
return String.raw({ raw: strings }, ...values)
}
let content1 = '<script>alert(1)</script>'
let content2 = '<script>alert(2)</script>'
let htmls = safeHtmlraw`${content1} is safe html, ${content2} too!`
console.log(htmls)