Faster, Higher, Stronger
更快,更高,更强

Highlight template code

Today, an frontend developer want to implement an effect — to highlight template code. As an example, we need to transfer string like “dfasf${1}${2tes}dfsdf${hello3}blabla”  to an array like:

["dfasf", "${1}", "${2tes}", "dfsdf", "${hello3}", "blabla"]

Here is my solution (in JavaScript):

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)

This function will return an array as we mentioned above.

赞(0) 打赏
未经允许不得转载:峰间的云 » Highlight template code

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

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

支付宝扫一扫打赏

微信扫一扫打赏