Dart String endsWith()
Syntax & Examples


Syntax of String.endsWith()

The syntax of String.endsWith() method is:

 bool endsWith(String other) 

This endsWith() method of String checks whether this string ends with other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe string to check if it's at the end of the original string

Return Type

String.endsWith() returns value of type bool.



✐ Examples

1 Check if string ends with 'world!'

In this example,

  1. We create a string str with the value 'Hello, world!'.
  2. We then use the endsWith() method to check if it ends with 'world!'. Since the given string ends with 'world!', the endsWith() method returns true.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Hello, world!';
  bool endsWithWorld = str.endsWith('world!');
  print('Ends with "world!": $endsWithWorld');
}

Output

Ends with "world!": true

2 Check if string ends with 'G'

In this example,

  1. We create a string str with the value 'ABCDEF'.
  2. We then use the endsWith() method to check if it ends with 'G'. Since the given string does not end with 'G', the endsWith() method returns false.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'ABCDEF';
  bool endsWithG = str.endsWith('G');
  print('Ends with "G": $endsWithG');
}

Output

Ends with "G": false

3 Check if string ends with 'amet'

In this example,

  1. We create a string str with the value 'Lorem ipsum dolor sit amet'.
  2. We then use the endsWith() method to check if it ends with 'amet'. Since the given string ends with 'amet!', the endsWith() method returns true.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Lorem ipsum dolor sit amet';
  bool endsWithAmet = str.endsWith('amet');
  print('Ends with "amet": $endsWithAmet');
}

Output

Ends with "amet": true

Summary

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