decode method Null safety

String decode(
  1. String string
)

Parses a string and replaces all valid HTML character entities with their respective characters.

Implementation

static String decode(String string) {
  var charCodeIndex = 0;

  Match? findNextCharCode() {
    final Iterable<Match> charCodes =
        RegExp(r'&(#?)([a-zA-Z0-9]+?);').allMatches(string);

    if (charCodes.length <= charCodeIndex) return null;

    return charCodes.elementAt(charCodeIndex);
  }

  var nextCharCode = findNextCharCode();

  while (nextCharCode != null) {
    var charCode = string.substring(nextCharCode.start, nextCharCode.end);

    if (charCode.startsWith(RegExp(r'&#[x0]'))) {
      while (charCode.startsWith(RegExp(r'&#x?0'))) {
        charCode = charCode.replaceFirst('0', '');
      }

      charCode = charCode.toLowerCase();
    }

    if (characters.containsKey(charCode)) {
      string = string.replaceRange(
          nextCharCode.start, nextCharCode.end, characters[charCode]!);
    } else {
      charCodeIndex++;
    }

    nextCharCode = findNextCharCode();
  }

  return string;
}