convertToIdentifier function

String convertToIdentifier(
  1. String identifer, {
  2. String prefix = 'a',
})

Converts a string to a valid dart identifier. For example, by replacing invalid characters, and ensuring the string is prefixed with a letter or underscore.

Implementation

String convertToIdentifier(String identifer, {String prefix = 'a'}) {
  assert(isValidIdentifier(prefix));

  // The current implementation is a bit naive, but it works for now.
  // Consider replacing with a dart port of https://github.com/avian2/unidecode
  identifer = identifer.replaceAll(RegExp(r'[^A-Za-z0-9_]'), '_');
  if (!identifer.startsWith(RegExp(r'[A-Za-z]'))) {
    identifer = '$prefix$identifer';
  }
  return identifer;
}