Reputation: 2311
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?
Upvotes: 0
Views: 42
Reputation: 2311
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.
}
Upvotes: 1