Input field value - remove leading zeros

前端 未结 8 1917
南笙
南笙 2020-11-27 06:34

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.0

8条回答
  •  猫巷女王i
    2020-11-27 07:01

    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:

    Replaces with:

    • ^ 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 ()

提交回复
热议问题