Skip to content

如何高亮模版代码

今天有个前端朋友说想要实现模版代码高亮,就是把一个模版字符串里的变量部分高亮出来。简化一下后就是要把`"dfasf1{2tes}dfsdfhello3blabla"\`span{}的数组元素另外加一个特别的class单独给个高亮样式就可以了): ```text ["dfasf", "1","{2tes}", "dfsdf", "hello3","blabla"\]\`\`\`\`\`\`jsconststrDemo=dfasf{1}2tesdfsdf{hello3}blabla' function getChilds (str) { const arr = [] while (str.length > 0) { const match = str.match(/\$\{.*?\}/) if (match === null) { arr.push(str) str = '' continue } if (match !== null) { const matchStr = match[0] const matchIdx = match.index const matchLength = matchStr.length if (matchIdx !== 0) { arr.push(str.substring(0, matchIdx)) } arr.push(matchStr) str = str.substr(matchIdx + matchLength) } } return arr } getChilds(strDemo) ``` 这个方法会返回上面我们期望得到的数组。

天上的神明与星辰,人间的艺术和真纯,我们所敬畏和热爱的,莫过于此。