How to Remove Special Characters from String in Dart/Flutter

In this post, we are going to show how to extract alphabets or numbers only from String by removing special characters. We will use RegEx expression to remove special characters from String in Dart or Flutter. 

String str = "#@F&L^&%U##T#[email protected]#ER###[email protected]#@M*([email protected]&#S%^%[email protected]*(^&";
String result = str.replaceAll(RegExp('[^A-Za-z0-9]'), '');
print(result); //Output: FLUTTERCAMPUS2324

Here, we have string "str" with special characters, alphabets, numbers. We have used the replaceAll() method on string with RegEx expression to remove the special characters. It will give you the alphabets and numbers both and Special characters will be removed.

String str1 = "#@F&L^&%U##T#[email protected]#ER###[email protected]#@M*([email protected]&#S%^%[email protected]*(^&";
String result1 = str1.replaceAll(RegExp('[^A-Za-z]'), '');
print(result1); //Output (Allphabets Only): FLUTTERCAMPUS 

Here, we used RegEx expression and the replaceAll method to remove social characters, numbers and only get the alphabets. You can also modify the RegEx expression to get capital or small letter only alphabets in Dart or Flutter.

String str2 = "#@F&L^&%U##T#[email protected]#ER###[email protected]#@M*([email protected]&#S%^%[email protected]*(^&";
String result2 = str2.replaceAll(RegExp('[^0-9]'), '');
print(result2); //Output (Numbers Only): 2324

This code will give you only numbers by removing alphabets and special characters from String in Dart or Flutter.

String str3 = "#@F&L^&%U##T#[email protected]#ER###[email protected]#@M*([email protected]&#S%^%[email protected]*(^&";
String result3 = str3.replaceAll(RegExp('[^A-Za-z0-9]'), '.');
print(result3); 
//Output: ..F.L...U..T.T..ER...CA...M..PU...S...2324.....

You can use the above code to replace special characters with any other characters, you can replace '.' with your own characters.

In this way, you can remove Special characters from String in Dart or Flutter. 

No any Comments on this Article


Please Wait...