Regex for stripping leading zeroes

Hello, all,

I’m trying to come up with a replace regex that will allow either a single zero, or will allow a number without leading zeroes.

The regex I have, right now, will allow only numbers, but I can’t figure out how to remove everything else if a single zero is entered, first.

$(this).val($(this).val().replace(/[^\d]/gi,''));

V/r,

:slight_smile:

One possibility:

replace(/\D*0*(\d).*/gi,'$1')

The following regular expression removes all zeros and non-digits at the start of your string.

replace(/^[0|\D]*/,'');

This means:
^ start at the beginning
[0|\D]* find all sequential zeros or non-digit characters. The * means all or none of this group.

examples:
00001234 becomes 1234
0A001234 becomes 1234
1234A becomes 1234A

I am assuming that the starting characters are the only ones you are interested in.

@felgall and @AllanP, thank you for replying.

What I’m trying to achieve is (using onkeyup):
If someone enters a non-integer character anywhere in the string, it is removed.
If someone enters a zero, nothing else is accepted (but the single zero stays).
Any and all integers are allowed.
Examples:
0000 cannot be entered because everything after the first 0 is removed and stays as ‘0’
0ad7b0rt_x becomes 0 (see above)
asdf becomes blank
1000000000 is accepted
10000asdf0 cannot be entered because ‘asdf’ will be removed, so this becomes 100000 (the current regex will do this)

@AllanP, unless I am missing something, I think your regex will strip all leading zeroes, I believe not allowing an initial single zero to be entered. This is for a monetary value input, and the user should be allowed to say “zero dollars”. I just don’t want some joker to enter “00” or “0.00”.

@felgall, thank you; I’ll give that a shot and report back.

V/r,

:slight_smile:

UPDATE: @felgall’s regex (as entered) will allow a single integer and nothing else. If 1 through 9 is entered, it will stay and everything else after it will be removed. If a 0 is entered, any non-integer entered after it will be removed, but any other integer will replace the 0, and everything entered after will be replaced. Much appreciated, but it is not producing the desired results.

Not the greatest solution, BUT…

$(this).val($(this).val().replace(/[^\d]/gi,'').replace(/^0{1,}\d+/,'0'));

Slightly hackish, but it is producing the desired results. If anyone can think of how to slim this down to a single replace() instead of two, please LMK.

V/r,

:slight_smile:

Well, except 0100 will become 0.

From what I understand, the rules are no non-digits and no leading 0’s, right?

.replace(/\D|^0+/g, '')

That being said, as a user, I’m very much not a fan of my input being changed on every keystroke. On occasion, I goof and enter a value awkwardly, and munging my value while I’m still trying to enter it is frustrating. Wait until I say I’m ready.

Take a look at jQuery maskMoney plugin, maybe this is what you need

Which is in my list of requirements for the regex. If a user enters a 0 first, nothing else should be allowed.

V/r,

:slight_smile:

Appreciated, but I’d rather not parseFloat(), Number(), or do anything else to strip out currency symbols, commas, or decimals. Simple integers, that’s all.

V/r,

:slight_smile:

For readability, I think I would implement this as two separate RegExes.
But as noted above, try not to be too aggressive with it - if possible, I would allow the user to input anything they like, and then interpret it later on.

It has a method to return unmasked value (without currency and separators):

.maskMoney(‘unmasked’) return a float value (ex.: ‘R$ 1.234,56’ => 1234.56)

And you can disable decimals with an option

What happens if they paste a value in?

Here’s a specific and real-life example of how it could go down. Let’s say I want to enter 101, but maybe my keyboard sticks, or maybe I whiffed the key, and I miss the first “1”, so instead I end up typing “01”, which would actually come out as just 0 with your rules. “Oops,” I say, and I try to fix it. I type one of the missing 1’s… nothing happens. Okay… I click to move the cursor before the zero, and type a “1”… nothing happens. Now I’m thinking, “What the f—k is wrong with this website?!”

Already tested. Works as desired. If a 0 is entered, first, and the cursor moved to before the 0 and any other number is entered, it enters before the zero - action is on keyup, not keydown.

As far as pasting a value in, I haven’t tried, yet, but I am using the onpaste attribute, as well as the onblur, so even if it is pasted in with an undesired value, the blur will fix it.

V/r,

:slight_smile:

left out a + in what I thought you were after

replace(/\D0(\d+).*/gi,‘$1’)

note that this matches what you titled the thread of stripping leading zeros and not what you have since said to stop when a zero is entered.

These regex’s are getting highly complicated and should never be used in production.

What’s wrong with using a simple if/else condition?

If (this.value = "0") {
    // allow zero to remain
} else {
    // do your regex here
}

Keep it simple, for with complex code the ability to understand it fades with time, and checking later on if there are any bugs becomes near-impossible.

You need to split the problem into three sections:

  • Test if the string is a number
  • If it is a number strip the leading unwanted characters
  • test if the stripped result length is zero. if it is the original string was only zeros and can be written back as"0"

Here is the script to do it.

<script type="text/javascript">
var test="001234";  // <<<<<<<<<<<<<<<<<<<  CHANGE THIS TO TEST
var result, regexp;
if(isNaN(test)===true) {result="Not a number"; }      
else{ // Is a number so strip leading chars
      regexp=/^[0|\D]*/g;
      result=test.replace(regexp,'');          
     } 
// check for only zeros     
if(result===""){result="0"; }     
document.write("test= "+test+" result= >"+result+"<");
</script>

The result will be written to your page.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.