N Kaushik

How to replace a substring in dart string

May 06, 2020

Replace substring in a dart string :

dart provides one method called replaceAll that can be used to replace one substring with a given string. This method is defined as below :

String replaceAll(Pattern p, String r)

The pattern p can be a regular expression or simply a substring.

Example 1: Replace one character :

We can simply pass one character as the first character to replace it with another character :

void main() {
  print('nkaushikd'.replaceAll('n','N'));
}

It will print :

Nkaushikd

Example 2: Replace one substring :

We can also replace one substring :

void main() {
  print('nkaushikd'.replaceAll('nkaushik','N'));
}

Output :

Nd

Example 3: Using a pattern :

We can use one regular expression as well. The below example replaces all special characters with a blank empty character :

void main() {
  print('nkau##shi*()&*kd@\$!'.replaceAll(RegExp(r'[^A-Za-z0-9]'),''));
}

It will print :

nkaushikd

Subscribe to my Newsletter