简体   繁体   中英

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

I'm using gulp to generate HTML pages from tempaltes.

The templates look like this:

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

I am trying to replace the placeholder with some minified JS code .

My gulp build uses a method that looks like this:

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 .

It replaced the {placeholder} with the minified JS code, and then it replaced the "$&" with the value "{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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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