regex: remove leading zeros, but keep single zero

tilly :

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.

anubhava :

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');

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=278895&siteId=1