Home > Blockchain >  How to remove a certain part of a string in Dart?
How to remove a certain part of a string in Dart?

Time:10-16

I am sure the solution is pretty simple.

I want to reduce a String by another String which is contained in the first one.

Here is my code

String street = "2576 Lombard St"
String houseNumber = "2576"

I only need a function to remove the house Number from the String "street". So the endresult should look like this:

String streetname = "Lombard St"

CodePudding user response:

The following code will do what you want

    const String street = '2576 Lombard St';
    const String houseNumber = '2576';
    final String streetName = street.replaceAll(houseNumber, '').trim();
    print('Street name: $streetName'); // Street name: Lombard St

If you want to remove all digits

    const String street = '2576 Lombard St';
    const String houseNumber = '2576';
    final String streetName = street.replaceAll(RegExp(r'\d '), '').trim();
    print('Street name: $streetName'); // Street name: Lombard St

If you only want to remove the first houseNumber;

    const String street = '2576 Lombard St';
    const String houseNumber = '2576';
    final String streetName = street.replaceFirst(houseNumber, '');
    print('Street name: $streetName'); // Street name: Lombard St

CodePudding user response:

You can use .replaceAll on String.

String removeHouseNumber(String street, String houseNumber) {
  return street.replaceAll(houseNumber, "").trim();
}

String street = "2576 Lombard St";

String houseNumber = "2576";
print(removeHouseNumber(street,houseNumber)); //Lombard St
  • Related