Dart – Trim String

Welcome to tutorial on trimming a String.

To trim leading and trailing spaces or white space characters of a given string in Dart, you can use trim() method of String class.

The syntax of trim() class is:

String.trim()

String.trim() returns a new string with all the leading and trailing white spaces of this string removed.

Example – Trim String

In this example, we will take a string and trim its edges of white spaces.

Dart Program

void main(){
	
	String str = '   Hello TutorialKart         ';
	
	//trim string
	String result = str.trim();
	
	print(result);
}

Output

Hello TutorialKart

Example – Trim String with Tabs and New Line characters at the edges

In this example, we will take a string with spaces, tabs and new line characters at its edges and then use trim() to trim these white characters off.

Dart Program

void main(){
	
	String str = ' \n\n\t \t  Hello TutorialKart    \t  \n   ';
	
	//trim string
	String result = str.trim();
	
	print(result);
}

Output

Hello TutorialKart

Conclusion

In this Dart Tutorial, we learned how to trim a String using the method String.trim().