Dart String startsWith()
Syntax & Examples


Syntax of String.startsWith()

The syntax of String.startsWith() method is:

 bool startsWith(Pattern pattern, [int index = 0]) 

This startsWith() method of String checks whether this string starts with a match of pattern.

Parameters

ParameterOptional/RequiredDescription
patternrequiredthe pattern to search for within the string
indexoptional [default value is 0]if provided, matching will start at this index

Return Type

String.startsWith() returns value of type bool.



✐ Examples

1 Check if string starts with 'Hello'

In this example,

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

Dart Program

void main() {
  String str = 'Hello, world!';
  bool startsWithHello = str.startsWith('Hello');
  print('Starts with \'Hello\' in str: $startsWithHello');
}

Output

Starts with 'Hello' in str: true

2 Check if string starts with 'A'

In this example,

  1. We create a string str with the value 'ABCDEF'.
  2. We then use the startsWith() method to check if it starts with 'A'.
  3. Since the given string starts with 'A', the startsWith() method returns true.
  4. We print the result to standard output.

Dart Program

void main() {
  String str = 'ABCDEF';
  bool startsWithA = str.startsWith('A');
  print('Starts with \'A\' in str: $startsWithA');
}

Output

Starts with 'A' in str: true

3 Check if string starts with 'Lorem'

In this example,

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

Dart Program

void main() {
  String str = 'Lorem ipsum dolor sit amet';
  bool startsWithLorem = str.startsWith('Lorem');
  print('Starts with \'Lorem\' in str: $startsWithLorem');
}

Output

Starts with 'Lorem' in str: true

Summary

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