Dart – Trim 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.

Syntax

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.

ADVERTISEMENT

Examples

Trim String of Whitespaces

In this example, we will take a string str and trim its edges of whitespaces.

Dart Program

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

Output

Hello TutorialKart

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().