[英]String contains the replaced value after using replace (Regex.lastMatch)
我正在用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>
...
它怎么可能替換工作,以及{}占位符仍然出現在它的中間 ?
經過數小時的調試,我發現縮小的代碼包含字符“ $&”。
這種組合觸發了稱為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.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.