立诚勿怠,格物致知
It's all about connecting the dots

如何高亮模版代码

今天有个前端朋友说想要实现模版代码高亮,就是把一个模版字符串里的变量部分高亮出来。简化一下后就是要把"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)

这个方法会返回上面我们期望得到的数组。

赞(0) 打赏
文章名称:《如何高亮模版代码》
文章链接:https://www.orzzone.com/highlight-template-code.html
商业联系:yakima.public@gmail.com

本站大部分文章为原创或编译而来,对于本站版权文章,未经许可不得用于商业目的,非商业性转载请以链接形式标注原文出处。
本站内容仅供个人学习交流,不做为任何投资、建议的参考依据,因此产生的问题需自行承担。

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力提供更多优质内容!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册