injectAsChildOf static method

String injectAsChildOf(
  1. String htmlTag,
  2. String source,
  3. String toInject
)

Inject toInject as a child of the specified htmlTag. The htmlTag can be, for example, head or body.

The way it works is that it will take the whole htmlTag, including it's attributes (if any), and it will append toInject to it, such as the original htmlTag will now have toInject as it's first child (by child we mean HTML DOM child)

Implementation

static String injectAsChildOf(
    String htmlTag, String source, String toInject) {
  final replaceSpot = '<$htmlTag([^>]*)>';
  return source.replaceFirstMapped(RegExp(replaceSpot, caseSensitive: false),
      (match) {
    return '<$htmlTag${match.group(1)!}> \n$toInject';
  });
}