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
Parameter | Optional/Required | Description |
---|---|---|
pattern | required | the pattern to split the string |
onMatch | optional | function called for each match, returning a replacement string |
onNonMatch | optional | function 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,
- We create a string
str1
containing some words and numbers. - We use the
splitMapJoin()
method with a regular expression patternRegExp('\[0-9]+')
to split the string on numbers. - We provide
onMatch
andonNonMatch
functions to enclose matches in square brackets and non-matches in angle brackets, respectively. - 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,
- We create a string
str3
with the value 'Lorem ipsum dolor sit amet'. - We use the
splitMapJoin()
method with a regular expression patternRegExp(r'[a-z]+')
to split the string on sequence of lowercase letters. - We provide
onMatch
andonNonMatch
functions to enclose matches in square brackets and non-matches in angle brackets, respectively. - 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.