js 字符串模板实列(附带变量高亮处理,xss初步拦截)
//字符串模板 const Leo = { name:'Leo', date:'2019-12-21', todos:[ {name:'Go to Store',completed:false}, {name:'Watch Movie',completed:true}, {name:'Running',completed:true}, ] } function rendertudos(){ return ` <ul> ${Leo.todos.map((todo) => ` <li> ${todo.name} ${todo.completed ? 'OK' : 'NO'} </li>`).join('') } </ul> ` } const template = ` <div> ${rendertudos()} </div> ` document.body.innerHTML = template console.log(template)
//特殊变量高,并且初步拦截Xss攻击。需要引入DOMPurify插件。https://cdn.bootcss.com/dompurify/2.0.3/purify.min.js
function highlight(strs,...values){
console.log(strs)
console.log(values)
const heighlighted = values.map((vals) => `<span style="background-color:#f00">${vals}</span>`)
let str = ''
return strs.reduce((prev,curr,i) => `${prev}${curr}${heighlighted[i] || ''}`,'')
// strs.forEach((string,i) => str+= `${string} ${heighlighted[i] || ''}`)
// return str
}
function sanitze(strs,...values){ //初步过滤XSS攻击
const dirty = strs.reduce((prev,curr,i) => `${prev}${curr}${values[i] || ''}`,'');
return DOMPurify.sanitize(dirty)
}
const user = 'Leo'
const topic = 'Learn to use markdown'
const sentence = highlight`${user} has commented on your topic ${topic}`
const goji = sanitze`${user} has commented on your topic ${topic}` //可以过滤用户输入的alert等攻击
console.log(sentence)
document.body.innerHTML = sentence+goji
如果对小哥哥小姐姐有帮助请点个推荐哈,欢迎留言、评论、搞事!! 双肩背包 【正品折扣专业店】 -- biy1314.taobao.com