Dart/Flutter – How to replace all special characters in a String

In this post, I will show you a simple example of how to replace all special characters in a String using replaceAll method and RegExp (regular expression).

Note: special characters in our case are all characters that are:

  • Not alphabets (a-z or A-Z)
  • Not numbers (0-9)
/// Replace all special characters by a dot
Future<void> main() async {
  const String text = r'abc-dfs@#$#%#$This';
  final result = text.replaceAll(RegExp('[^A-Za-z0-9]'), '.');
  print(result);
}

// Output
abc.dfs.......This

If you want to remove all special characters, just simply replace the dot in above code by an empty string:

/// Remove all special characters
Future<void> main() async {
  const String text = r'abc-dfs@#$#%#$This';
  final result = text.replaceAll(RegExp('[^A-Za-z0-9]'), '');
  print(result);
}

// Output
abcdfsThis
Tagged : / / / / / / /
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x