How remove leading 0 in a string How remove leading 0 in a string dart dart

How remove leading 0 in a string


You could use RegExp which may be uglier but faster than double conversion :

"01".replaceAll(new RegExp(r'^0+(?=.)'), '')

´^´ matches the begining of the string

0+ matches one or more 0 character

(=?.) matches a group (()) of any characters except line breaks (.) without including it in the result (=?), this ensures that not the entire string will be matched so that we keep at least one zero if there are only zeroes.

Example :

void main() {  final List nums = ["00", "01", "02", "10", "11"];  final RegExp regexp = new RegExp(r'^0+(?=.)');  for (String s in nums) {    print("$s => ${s.replaceAll(regexp, '')}");  }}

Result :

00 => 001 => 102 => 210 => 1011 => 11

EDIT : Performance test thanks to your comment

void main() {  Stopwatch stopwatch = Stopwatch()..start();  final RegExp reg = RegExp(r'^0+(?=.)');  for (int i = 0; i < 20000000; i++) {    '05'.replaceAll(reg, '');  }  print('RegExp executed in ${stopwatch.elapsed}');  stopwatch = Stopwatch()..start();  for (int i = 0; i < 20000000; i++) {    int.parse('05').toString();  }  print('Double conversion executed in ${stopwatch.elapsed}');}

Result :

RegExp executed in 0:00:02.912000Double conversion executed in 0:00:03.216000

The more operations you will do the more it will be efficient compared to double conversion. However RegExp may be slower in a single computation because creating it has a cost, but we speak about a few microseconds... I would say that unless you have tens of thousands of operations just use the more convenient to you.


I think you have the most elegant form already! There options for toStringAsFixed (https://api.dart.dev/stable/1.19.1/dart-core/num/toStringAsFixed.html, mostly floating points) and NumberFormat (https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html), but I feel these might not cover your case


If anyone is trying to prevent leading zeros in a TextField, I made a TextInputFormatter that will remove all leading zeros once a non-zero number is added.

class NoLeadingZeros extends TextInputFormatter {  @override  TextEditingValue formatEditUpdate(TextEditingValue oldValue,TextEditingValue newValue,  ) {if (newValue.text.startsWith('0') && newValue.text.length > 1) {  return TextEditingValue().copyWith(    text: newValue.text.replaceAll(new RegExp(r'^0+(?=.)'), ''),    selection: newValue.selection.copyWith(      baseOffset: newValue.text.length - 1,      extentOffset: newValue.text.length - 1,    ),  );} else {  return newValue;}  }}

The tricky part is adjusting the TextSelection offsets once the zeros are removed. Without this update, the TextField will stop working.