我正在使用gulp从tempaltes生成HTML页面。
模板如下所示:
...
<script type="application/javascript">
{placeholder}
</script>
...我试图用一些精简的JS代码替换占位符。
我的gulp使用了如下方法:
function renderTemplate(minifiedJS) {
var template = fs.readFileSync('template.html', 'utf-8');
return template.replace('{placeholder}', minifiedJS); // this is ok because the {placeholder} appears only once.
}然而,结果如下所示:
...
<script type="application/javascript">
MINIFIED JS CODE{placeholder}SOME MORE MINIFIED JS CODE
</script>
...如何使替换生效,并且{占位符}仍然出现在它的中间?
发布于 2018-01-26 14:54:00
经过几个小时的调试,我发现缩小后的代码包含了"$&“字符。
这种组合触发了一个名为RegExp.lastMatch的Regex特性。
它将{占位符}替换为精简的JS代码,然后将"$&“替换为”{占位符}“。
是啊。
最后,我将实现更改为
function renderTemplate(minifiedJS) {
var template = fs.readFileSync('template.html', 'utf-8');
var splitTemplate = template.split('{placeholder}');
return splitTemplate[0] + minifiedJS + splitTemplate[1]; // this is ok because the placeholder appears exactly once.
}https://stackoverflow.com/questions/48463833
复制相似问题