跳到主要内容

模版字符串解析

function render(template, data) {
return template.replace(/\{\{([^\}]+)\}\}/g, (str, $1) => {
return data[$1]
})
}

测试代码

const template = '我是{{name}},年龄{{age}},性别{{sex}}'
const data = {
name: '姓名',
age: 18,
}
console.log(render(template, data))

正则其他方法测试代码

const reg = /hello/g
console.log(reg.exec('hellohello'), reg.lastIndex)
console.log(reg.exec('hellohello'), reg.lastIndex)
console.log(reg.exec('hellhello'), reg.lastIndex)

console.log(reg.test('hellhello'), reg.lastIndex)
console.log(reg.test('hellhello'), reg.lastIndex)

console.log('hellohello'.search(reg))
console.log('hellohello'.search(reg))

console.log('hellohello'.match(reg), reg.lastIndex)
console.log('hellohello'.match(reg), reg.lastIndex)

console.log(
'hellohello'.replace(reg, (...args) => {
console.log(...args)
return 'i'
}),
)