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
Thanks. How can we replace these characters (芒,没,卯, 脗, 脹, 脦) in the String?