Input field value - remove leading zeros

Viewed 60676

I have a textbox in Javascript. When I enter '0000.00' in the textbox, I want to know how to convert that to only having one leading zero, such as '0.00'.

8 Answers

More simplified solution is as below. Check this out!

var resultString = document.getElementById("theTextBoxInQuestion")
                           .value
                           .replace(/^[0]+/g,"");
var value= document.getElementById("theTextBoxInQuestion").value;
var number= parseFloat(value).toFixed(2);

It sounds like you just want to remove leading zeros unless there's only one left ("0" for an integer or "0.xxx" for a float, where x can be anything).

This should be good for a first cut:

while (s.charAt(0) == '0') {            # Assume we remove all leading zeros
    if (s.length == 1) { break };       # But not final one.
    if (s.charAt(1) == '.') { break };  # Nor one followed by '.'
    s = s.substr(1, s.length-1)
}

Try this:

<input type="text" onblur="this.value=this.value.replace(/^0+(?=\d\.)/, '')">

You can use a regex to replace the leading zeroes with a single one:

valueString.replace(/^(-)?0+(0\.|\d)/, '$1$2')

>'-000.0050'.replace(/^(-)?0+(0\.|\d)/, '$1$2')
< "-0.0050"
>'-0010050'.replace(/^(-)?0+(0\.|\d)/, '$1$2')
< "-10050"

Matches: <beginning of text><optional minus sign><any sequence of zeroes><either a zero before the dot or another digit>

Replaces with: <same sign if available><the part of the string after the sequence of zeroes>

  • ^ is the beginning of text

  • ? means optional (refers to the previous character)

  • (a|b) means either a or b

  • . is the dot (escaped as . has a special meaning)

  • \d is any digit

  • $1 means what you found in the first set of ()

  • $2 means what you found in the second set of ()

Related