简体   繁体   English

字符串包含使用替换后的替换值(Regex.lastMatch)

[英]String contains the replaced value after using replace (Regex.lastMatch)

I'm using gulp to generate HTML pages from tempaltes. 我正在用gulp从临时模板生成HTML页面。

The templates look like this: 模板如下所示:

...
<script type="application/javascript">
{placeholder}
</script>
...

I am trying to replace the placeholder with some minified JS code . 我试图用一些缩小的JS代码替换占位符。

My gulp build uses a method that looks like this: 我的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.
}

However, the result looks something like this: 但是,结果看起来像这样:

...
<script type="application/javascript">
 MINIFIED JS CODE{placeholder}SOME MORE MINIFIED JS CODE
</script>
...

How can it be that the replace worked, and the {placeholder} still appears in the middle of it? 它怎么可能替换工作,以及{}占位符仍然出现在它的中间

After hours of debugging, I found that the minified code contained the characters "$&". 经过数小时的调试,我发现缩小的代码包含字符“ $&”。

This combination triggered a Regex feature called RegExp.lastMatch . 这种组合触发了称为RegExp.lastMatch的正则表达式功能。

It replaced the {placeholder} with the minified JS code, and then it replaced the "$&" with the value "{placeholder}". 它用最小的JS代码替换了{placeholder},然后用值“ {placeholder}”替换了“ $&”。

Yep. 是的。

I ended up changing the implementation to 我最终将实现更改为

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM