Dart – Replace Substring in String

Welcome to tutorial on Replacing sub-string with Another sub-string in a String.

To replace all occurrences of a substring in a string with new substring, use String.replaceAll() method.

The syntax of replaceAll() method is:

String.replaceAll(Pattern pattern, String newSubString)

The method returns a new string with all string matchings of given pattern replaced with newSubString. You can give a string for pattern.

Example – Replace Substring in String

In this example, we will take a string and replace Hello with Hi in that String.

Dart Program

void main(){
	
	String str = 'Hello TutorialKart. Hello User.';
	
	//replace subString
	String result = str.replaceAll('Hello', 'Hi');
	
	print(result);
}

Output

Hi TutorialKart. Hi User.

Example – Replace Substring in String

In this example, we will take a string and replace Ola with Hi in that String. But, the string does not contain Ola. Let us see what happens.

Dart Program

void main(){
	
	String str = 'Hello TutorialKart. Hello User.';
	
	//replace subString
	String result = str.replaceAll('Ola', 'Hi');
	
	print(result);
}

Output

Hello TutorialKart. Hello User.

Since there is no match for the provided pattern, copy of the original string is returned by replaceAll().

Example – Chaining replaceAll() method

You can chain replaceAll() method. In this example, we will chain replaceAll() method. Please observe the following Dart program.

Dart Program

void main(){
	
	String str = 'Hello TutorialKart. Hello User.';
	
	//replaceAll() chaining
	String result = str.replaceAll('Hello', 'Hi').replaceAll('User', 'Client');
	
	print(result);
}

Output

Hi TutorialKart. Hi Client.

First replaceAll() replaces Hello with Hi, and then on this resulting string, second replaceAll() replaces User with Client.

Conclusion

In this Dart Tutorial, we learned how to replace all occurrences of a substring with another in a string using replaceAll().