今天有个前端朋友说想要实现模版代码高亮,就是把一个模版字符串里的变量部分高亮出来。简化一下后就是要把"dfasf${1}${2tes}dfsdf${hello3}blabla"
这个字符串转换成下面这样的数组(转成数组后每个数组元素外面包一个span标签,带${}的数组元素另外加一个特别的class单独给个高亮样式就可以了):
["dfasf", "${1}", "${2tes}", "dfsdf", "${hello3}", "blabla"]
以下为我的解决方案:
const strDemo = 'dfasf${1}${2tes}dfsdf${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)
这个方法会返回上面我们期望得到的数组。