简体   繁体   中英

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. eg "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.

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

A simple reg exp with leading zeros and match one digit in a capture group

 const cleanZeros = str => str.replace(/^0+(\\d)/, '$1') var tests = ["0009876","0", "0000", "9999", "0090000"] tests.forEach( s => console.log(s, cleanZeros(s)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM