C#桌面工具:用霍夫变换自动纠正拍照文档的歪斜角度
2026/6/4 14:32:25
问题:实现template方法,替换模板中的变量
consttpl=`<p> hello, my name is <%= name%>, my age is <%= age %>`letdata={name:'jerry',age:18}letresult=template(tpl,data)console.log(result)//输出<p> hello, my name is jerry my age is 18实现:replace方法,正则匹配
(\w+) 捕获组(关键部分):
// match是匹配到的<%= name %>, 是被替换的目标;
// key是通过(\w+)捕获到的分组内容,如 name ;
// 回调函数的返回值会替换掉match对应的内容。
functiontemplate(tpl,data){returntpl.replace(/<%=\s*(\w+)\s*%>/g,(match,key)=>{returndata[key]??''//从data中取值,如果不存在则返回空字符串})}