Reputation: 23593
Im performing a find and replace with gulp.
I need to find this string below (ANYTHING can be anything, its not a string of 'ANYTHING'):
{% id_ANYTHING %}
And replace it with this:
{% block ANYTHING %}{% endblock %}
Example1.
Replace this:
{% id_page %}
With this:
{% block page %}{% endblock %}
Example2.
Replace this:
{% id_whatever %}
With this:
{% block whatever %}{% endblock %}
Ive found the regex that I need to find the match. Im already using gulp-replace for a similar but simpler task so Ive started using it for this but I'm not sure how to grab the 'anything' value so that I can use it in the replace.
https://github.com/lazd/gulp-replace
replace = function() {
return gulp.src('before.html')
.pipe(replace({
patterns:
[{
match: /{% id_.{2,99} %}/g,
replacement: '{% block page %}{% endblock %}'
}]
}))
.pipe(gulp.dest('after.html'));
},
Should I be looking to do this with Gulp or Node?
Upvotes: 1
Views: 1083
Reputation: 19428
Per the docs for gulp-replace
you can use a function for the replacement value, just like you can for String.prototype.replace()
Also, I've modified your RegEx to group the .{2,99}
together using ()
. The String.replace()
callback function will breakout each group as a separate arg. Since you're only interested in extracting that group, we can have String.replace()
do all the work and return back the value to replace the matched text.
const gulp = require('gulp')
const replace = require('gulp-replace');
const path = require('path');
let pattern = new RegExp(/{% id_(.{2,99}) %}/, 'g');
gulp.task('replace', () => {
return gulp.src('before.html')
.pipe(replace(pattern, (match, p1) => {
return `{% block ${p1} %} {% endblock %}`;
}))
.pipe(gulp.dest(path.join(__dirname, 'after.html')));
});
Upvotes: 2