slugify function

String slugify(
  1. String input, {
  2. int maxLength = 24,
})

Lower-case, ASCII-alphanumeric slug.

Implementation

String slugify(String input, {int maxLength = 24}) {
  final lowered = input.toLowerCase();
  final buf = StringBuffer();
  var lastWasSep = true;
  for (var i = 0; i < lowered.length; i++) {
    final c = lowered.codeUnitAt(i);
    final isLower = c >= 0x61 && c <= 0x7A;
    final isDigit = c >= 0x30 && c <= 0x39;
    if (isLower || isDigit) {
      buf.writeCharCode(c);
      lastWasSep = false;
    } else if (!lastWasSep) {
      buf.write('_');
      lastWasSep = true;
    }
  }
  var out = buf.toString();
  while (out.endsWith('_')) {
    out = out.substring(0, out.length - 1);
  }
  if (out.isEmpty) return 'node';
  if (out.length > maxLength) {
    out = out.substring(0, maxLength);
    while (out.endsWith('_')) {
      out = out.substring(0, out.length - 1);
    }
    if (out.isEmpty) return 'node';
  }
  return out;
}