Dart string splitMapJoin examples

Dart string splitMapJoin :

splitMapJoin is an utility method of dart string. It is used to split a string, convert its part and join the parts back to a new string.

Definition :

Below is the definition of this method :

String splitMapJoin (Pattern pattern,{String onMatch(Match m),String onNonMatch(String s)})

Here, pattern is used to define how to split the string.

onMatch will convert the matched parts to a string. If we remove it, the matched string is used by default.

onNonMatch is used to change the non-matched part. If we remove this, the non matching string is used by default.

Example of splitMapJoin with onMatch:

Suppose, we are logging user data on our application and we want to remove the sensitive information from logs. Let’s say user account number is a sensitive information and we need to replace it with *.

We can use splitMapJoin to do that easily. It will search for all numbers in a string and replace them with * like below :

main(List<string> args) {
  String s = "User card number : 9989893839";
  print(s.splitMapJoin((new RegExp(r'[0-9]')),
  onMatch: (m) => '*'));
}

Here, we are using one regular expression to match all numbers in the given string s. The onMatch is called for each matched character and it replaces the character with *.

If you run this program, it will print the below output :

User card number : **********

Dart splitMapJoin onMatch

Example of splitMapJoin with onMatch and onNonMatch:

The below example converts the characters to upper case if it doesn’t match with the provided pattern :

main(List<string> args) {
  String s = "User card number : 9989893839";
  print(s.splitMapJoin((new RegExp(r'[0-9]')),
      onMatch: (m) => '*', onNonMatch: (n) => n.toUpperCase()));
}

We are using onNonMatch here. This is called for all non-matching characters in the string. It will print the below output :

USER CARD NUMBER : **********

Dart splitMapJoin onMatch onNonMatch

Dart splitMapJoin comes in handy in many places. We can use it instead of splitting a string. What do you think ? Drop a comment below and like/subscribe to our blog if you find this useful :)

Similar tutorials :