Dart String replaceAll method

Published by admin on

Dart string replaceAll example

Introduction :

replaceAll is a dart string method that replaces part of a string defined by a pattern with a given value. It creates the new string and returns it.

 

Syntax :

replaceAll is defined as below :

String replaceAll(Pattern from, String replace)

Here,
from : Pattern to replace in the string.
replace : New replacement string.

You can pass one string or regular expression as the first parameter.

 

Example with a string :

main() {
  var givenString = "Hello World !!";
  print(givenString.replaceAll('World', 'Universe'));
}

It will print the below output :

Hello Universe !!

If the word exists multiple times :

main() {
  var givenString = "Hello World !! Hello World again !";
  print(givenString.replaceAll('World', 'Universe'));
}

Output :

Hello Universe !! Hello Universe again !

 

Using Regular expression :

We can use one regular expression as the first parameter in replaceAll :

main() {
  var givenString = "Thi2s is3 a4 string with character5s an3 numbers90";
  print(givenString.replaceAll(RegExp(r'[0-9]'), '*'));
}

It will print the below output :

Thi*s is* a* string with character*s an* numbers**

It replaced all numbers with *.

You can write any complex Regular expressions and use it in replaceAll.

Categories: dart

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *