Dart String splitMapJoin()
Syntax & Examples

Syntax of String.splitMapJoin()

The syntax of String.splitMapJoin() method is:

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

This splitMapJoin() method of String splits the string, converts its parts, and combines them into a new string.

Parameters

ParameterOptional/RequiredDescription
patternrequiredthe pattern to split the string
onMatchoptionalfunction called for each match, returning a replacement string
onNonMatchoptionalfunction called for each non-match, returning a replacement string

Return Type

String.splitMapJoin() returns value of type String.



✐ Examples

1 Split and map punctuation

In this example,

  1. We create a string str1 containing some words and numbers.
  2. We use the splitMapJoin() method with a regular expression pattern RegExp('\[0-9]+') to split the string on numbers.
  3. We provide onMatch and onNonMatch functions to enclose matches in square brackets and non-matches in angle brackets, respectively.
  4. We print the result to standard output.

Dart Program

void main() {
  String str1 = 'apple 1452 banana 452 cherry 74';
  var result3 = str1.splitMapJoin(
    RegExp('[0-9]+'),
    onMatch: (match) {
      print('Match: [${match.group(0)}]');
      return '[${match.group(0)}]';
    },
    onNonMatch: (nonMatch) {
      print('Non-Match: <$nonMatch>');
      return '<$nonMatch>';
    },
  );
}

Output

Non-Match: <apple >
Match: [1452]
Non-Match: < banana >
Match: [452]
Non-Match: < cherry >
Match: [74]
Non-Match: <>

2 Split and map words starting with 'i'

In this example,

  1. We create a string str3 with the value 'Lorem ipsum dolor sit amet'.
  2. We use the splitMapJoin() method with a regular expression pattern RegExp(r'[a-z]+') to split the string on sequence of lowercase letters.
  3. We provide onMatch and onNonMatch functions to enclose matches in square brackets and non-matches in angle brackets, respectively.
  4. We print the result to standard output.

Dart Program

void main() {
  String str3 = 'Lorem ipsum dolor sit amet';
  var result3 = str3.splitMapJoin(
    RegExp(r'[a-z]+'),
    onMatch: (match) {
      print('Match: [${match.group(0)}]');
      return '[${match.group(0)}]';
    },
    onNonMatch: (nonMatch) {
      print('Non-Match: <$nonMatch>');
      return '<$nonMatch>';
    },
  );
}

Output

Non-Match: <L>
Match: [orem]
Non-Match: < >
Match: [ipsum]
Non-Match: < >
Match: [dolor]
Non-Match: < >
Match: [sit]
Non-Match: < >
Match: [amet]
Non-Match: <>

Summary

In this Dart tutorial, we learned about splitMapJoin() method of String: the syntax and few working examples with output and detailed explanation for each example.