HTML Injector

HTML Injector

by Csaba Hellinger

JavaScript

class HtmlInjector {
  constructor(html) {
    this.html = html;
  }

  _inject(tagName, description, fragment) {
    const placeholderRegex = new RegExp(`\n?(</${tagName}>)`, 'i');
    this.html = this.html.replace(
      placeholderRegex,
      ['', `<!-- ${description} -->`, fragment, '$1'].join('\n')
    );
  }

  head(description, fragment) {
    this._inject('head', description, fragment);
  }

  body(description, fragment) {
    this._inject('body', description, fragment);
  }

  result() {
    return this.html;
  }
}
const injector = new HtmlInjector(`<html><head>aaa</head><body>bbb</body></html>`);

injector.head('the first to head', 'head1');
injector.head('the second to head', 'head2');
injector.body('script 1', 'body1');
injector.body('script 2', 'body2');

console.log(injector.result())