Handling HTML with regular expression is never advised, and there are many arguments (1, 2, 3) against that.
The most popular and reliable way to handle an HTML source is by constructing a document model of the source. JSDOM, is one node.js module that provides a good DOM construction API. Here's a demo of how to solve your case with JSDOM:
var fs = require("fs");
var gulp = require("gulp");
var dom = require("jsdom");
var domSerialiser = dom.serializeDocument;
var input = "input.html";
var output = "output.html";
gulp.task("copy-html", function () {
var extractionPoint = "#extraction-location";
var insertionPoint = "#insertion-location";
extractFrom(input, extractionPoint).
then(insertInto.bind(null, output, insertionPoint)).
then(saveOutput);
});
function extractFrom(file, section) {
return new Promise(function (resolve, reject) {
dom.env({
file: file,
done: function (error, window) {
var portion;
if (error) {
reject(error);
return;
}
portion = window.document.querySelector(section);
resolve(portion.outerHTML);
}
});
});
}
function insertInto(file, section, portion) {
return new Promise(function (resolve, reject) {
dom.env({
file: file,
done: function (error, window) {
if (error) {
reject(error);
return;
}
section = window.document.querySelector(section);
// you may prefer to appendChild() instead, your call
section.outerHTML = portion;
resolve(domSerialiser(window.document));
}
});
});
}
function saveOutput(data) {
fs.writeFile(output, data, function (error) {
if (error) {
throw error;
}
console.log("Copied portion to output successfully.");
});
}
I hope the example above provides a good basis for you to reach a solution specific to your issue.