2

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

Arun
  • 73
  • 2
  • 9

2 Answers2

1

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);
}
Vinay Jain
  • 398
  • 2
  • 6
  • Do I have to check for each reserved character and then replace them with other character using `replaceAll()`? Is there any other optimal solution that does the job in one go? – Arun Dec 16 '20 at 05:53
  • one solution is to add all reserved character in a list .Then iterate each character using a for loop and try to replace them. It's the only way then. Hope it helps. – Vinay Jain Dec 16 '20 at 05:56
  • Clearly not the only way, as illustrated by the other answers. – Randal Schwartz Dec 16 '20 at 17:50
0

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
}
Stefano Amorelli
  • 4,553
  • 3
  • 14
  • 30