Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex: remove leading zeros, but keep single zero

I have an input field to which I have tied a formatting function that is triggered whenever the field loses focus.

What I aim to achieve is that I remove all the leading zeros from an input and I did achieve that with the below line. However, when the user wants to enter a single 0 or something like 0000 I still want that field to end with the value 0 (single). With .replace(/^0+/, '') it would remove every zero and return just an empty string. Someone knows what regex could handle this?

const formatNumber = ($field) => {
var number = $field.val().replace(/\./g, '').replace(/\s/g, '').replace(/^0+/, '');
return number;
};

note: if(number === "") number = "0" is not an option.

edit1:: I noticed there seems to be a bit of confusion. e.g "0009825" need to become 9825 and not 09825. the only instance where i want a 0 up front is when the value is simply zero.

like image 544
tilly Avatar asked Oct 26 '25 06:10

tilly


1 Answers

You ay use this regex replacement:

.replace(/^(?:0+(?=[1-9])|0+(?=0$))/mg, '')

RegEx Demo

RegEx Details:

  • ^: Start
  • (?:: Start capture group
    • 0+(?=[1-9]): Match 1 or more zeroes that must be followed by 1-9
    • |: OR
    • 0+(?=0$): Match 1 or more zeroes that must be followed by one 0 and end
  • ): End capture group

Replacement is empty string which will leave a single 0 if there are only zeroes in string otherwise will remove leading zeroes.


Alternative solution using a capture group:

str = str.replace(/^0+(0$|[1-9])/mg, '$1');
like image 140
anubhava Avatar answered Oct 28 '25 20:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!