Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - Remove String after certain character?

Tags:

flutter

dart

What is the best way to remove all characters after specific character in the String object in Flutter?

Suppose that I have the following string:

one.two

and I need to remove the ".two" from it. How can I do it?

Thanks in advance.

like image 842
Shalugin Avatar asked Jan 16 '20 06:01

Shalugin


People also ask

How do you remove the string after a certain character in flutter?

' in the String it will use the first occurrance. If you need to use the last one (to get rid of a file extension, for example) change indexOf to lastIndexOf . If you are unsure there is at least one occurrance, you should also add some validation to avoid triggering an exception. if you want to remove only one.

How do I remove a specific character from a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do you trim string darts?

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. String. trim() returns a new string with all the leading and trailing white spaces of this string removed.


1 Answers

You can use the subString method from the String class

String s = "one.two";

//Removes everything after first '.'
String result = s.substring(0, s.indexOf('.'));
print(result);

In case there are more than one '.' in the String it will use the first occurrance. If you need to use the last one (to get rid of a file extension, for example) change indexOf to lastIndexOf. If you are unsure there is at least one occurrance, you should also add some validation to avoid triggering an exception.

String s = "one.two.three";

//Remove everything after last '.'
var pos = s.lastIndexOf('.');
String result = (pos != -1)? s.substring(0, pos): s;
print(result);
like image 159
Carlos Javier Córdova Reyes Avatar answered Oct 21 '22 20:10

Carlos Javier Córdova Reyes