jerrymouse
jerrymouse

Reputation: 17822

trim and remove specific characters from beginning and end of a string in dart

I am looking for a Dart function similar to python's strip function. Remove specific characters only from beginning and end.

String str = "^&%.      , !@  Hello @World   , *%()@#$ "
String newStr = str.strip("#*)(@!,^&%.$ ");

Result:

"Hello @World"

Upvotes: 8

Views: 5120

Answers (4)

jerrymouse
jerrymouse

Reputation: 17822

This following strip function should remove the special characters as provided.

String strip(String str, String charactersToRemove){
  String escapedChars = RegExp.escape(charactersToRemove);
  RegExp regex = new RegExp(r"^["+escapedChars+r"]+|["+escapedChars+r']+$');
  String newStr = str.replaceAll(regex, '').trim();
  return newStr;
}

void main() {
  String str = r"^&%.      , !@  Hello @World   , *%()@#$ ";
  String charactersToRemove = r"#*)(@!,^&%.$ ";
  print(strip(str, charactersToRemove));
}

Result:

Hello @World

PS

Raw string can be created by prepending an ‘r’ to a string. It treats $ as a literal character.

Upvotes: 3

Ronak Patel
Ronak Patel

Reputation: 629

If you want to remove whitespaces and special characters , anywhere from the string then try this,

String name = '4 Apple 1 k g @@ @ price50';  
print(name.replaceAll(new RegExp(r'[#*)(@!,^&%.$\s]+'), ""));

Output:- 4Apple1kgprice50

Upvotes: 1

Jigar Patel
Jigar Patel

Reputation: 5423

You can write an extension on String like this

void main() {
  String str = "^&%.      , !@  Hello @World   , *%()@#\$ ";
  String newStr = str.strip("#*)(@!,^&%.\$ ");                //<== Hello @World
}

extension PowerString on String {
  
  String strip(String whatToStrip){
    int startIndex, endIndex;
    
    for(int i = 0; i <= this.length; i++){
      if(i == this.length){
        return '';
      }
      if(!whatToStrip.contains(this[i])){
        startIndex = i;
        break;
      }
    }
    
    for(int i = this.length - 1; i >= 0; i--){
      if(!whatToStrip.contains(this[i])){
        endIndex = i;
        break;
      }
    }
    
    return this.substring(startIndex, endIndex + 1);
  }
  
}

Upvotes: 2

Mobina
Mobina

Reputation: 7119

You can use a regex to find the length of the leading and trailing part of the string that contain symbols. Then you can make a substring using the indices:

String str = "^&%.  ^    , !@  Hello@ World   , *%()@#\$ ";
RegExp regex = new RegExp(r'[#*)(@!,^&%.$\s]+');
int leftIdx = regex.stringMatch(str).length;
int rightIdx = regex.stringMatch(str.substring(leftIdx).split('').reversed.join('')).length;
String newStr = str.substring(leftIdx, str.length - rightIdx);

Result:

'Hello@ World'

Upvotes: 3

Related Questions