我正在使用 gulp 从模板生成 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>
...
替换成功后,{placeholder} 仍然出现在其中的中间,怎么可能?
最佳答案
经过几个小时的调试,我发现缩小后的代码包含字符“$&”。
此组合触发了名为 RegExp.lastMatch 的正则表达式功能。 .
它用缩小的 JS 代码替换了 {placeholder},然后用值“{placeholder}”替换了“$&”。
是的。
我最终将实现更改为
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.
}
关于javascript - 字符串包含使用替换后的替换值(Regex.last Match),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48463833/