Dart: Check whether a string starts/ends with a substring

Updated: March 31, 2023 By: A Goodman Post a comment

To check if a string starts with or ends with a given substring in Dart (and Flutter as well), you can use the startsWith() method and the endsWith() method, respectively:

bool x = myString.startsWith(mySubString);
bool y = myString.endsWith(mySubString);

These methods are case-sensitive (distinguish between uppercase and lowercase letters). If you want they to ignore case-sensitive, you can use regular expressions like so:

bool x = myString.startsWith(RegExp(mySubString, caseSensitive: false));
bool y = myString.endsWith(RegExp(mySubString, caseSensitive: false));

If you don’t clear on what I mean, please see the practical example below.

Example:

// main.dart
import 'package:flutter/foundation.dart';

void main() {
  const String s =
      'He thrusts his fists against the posts and still insists he sees the ghosts.';

  const String s1 = "He thrusts his fists";
  const String s2 = "HE THRUSTS HIS FISTS";
  const String s3 = "he sees the ghosts.";
  const String s4 = "the big ghosts.";

  if (kDebugMode) {
    print(s.startsWith(s1));
    print(s.startsWith(RegExp(s2, caseSensitive: false)));
    print(s.endsWith(s3));
    print(s.endsWith(s4));
  }
}

Output:

true
true
true
false

Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles