Dart – How to replace whitespace(s) between words in a string

Today, I had a “quite simple” requirement: Replace all whitespaces between two words in a string by a hyphen. For example:

"This is a string" -> "This-is-a-string"


Here is my first approach:

main() {
  final s1 = 'This is a string';
  print(replaceWhitespaces(s1, '-'));
}

String replaceWhitespaces(String s, String replace) {
  if (s == null) {
    return null;
  }

  return s.replaceAll(' ', replace);
}
// Output
This-is-a-string


This works well until I find the problem when the original string contains multiple whitespaces. Apply above solution, here is the output:

// Output
This---is----a------string


This is not what we expect. So that I have to change my approach using regular expression (RegExp):

main() {
  final s1 = 'This is a string';
  print(replaceWhitespacesUsingRegex(s1, '-'));

  final s2 = 'This   is    a      string';
  print(replaceWhitespacesUsingRegex(s2, '-'));
}

String replaceWhitespacesUsingRegex(String s, String replace) {
  if (s == null) {
    return null;
  }

  // This pattern means "at least one space, or more"
  // \\s : space
  // +   : one or more 
  final pattern = RegExp('\\s+');
  return s.replaceAll(pattern, replace);
}
// Output 
This-is-a-string // s1 after replacing
This-is-a-string // s2 after replacing
Tagged : / / / /
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x