remove reserved characters from a string in dart

Viewed 252

I found here that "|\\?*<\":>+[]/'" are reserved characters. How do I remove these characters from a string and replace them with -?

2 Answers

You can use replaceAll function to replace all similar characters to other characters of your choice. For eg:

void main() {
  String s="afas//f/saqhr";
  s=s.replaceAll("/","-");// replacing all / to -
  print(s);
}

For reusability's sake, I've created a Dart package.

To use it:

  1. Install

  2. Use the encode function as follows:

import 'package:safe_filename/safe_filename.dart' as SafeFilename;

void main() {
 String veryUnsafeFilename = 'File?Name<152.file';
 String safeFilename = (SafeFilename.encode(veryUnsafeFilename, onlyAlphanumeric: true, separator: '-', lowercase: true));
 print(safeFilename); // file-name-152.file
}
Related