12.7 C
New York
Tuesday, December 6, 2022

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

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:Advertisements

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

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

Example:

// main.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.";

  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.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles