Input field value - remove leading zeros

前端 未结 8 1833
南笙
南笙 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条回答
  • 2020-11-27 06:52
    str.replace(/^0+(?!\.|$)/, '')
    
      '0000.00' --> '0.00'   
         '0.00' --> '0.00'   
      '00123.0' --> '123.0'   
            '0' --> '0'  
    
    0 讨论(0)
  • 2020-11-27 06:54

    You can use this code:

    <script language="JavaScript" type="text/javascript">
    <!--
    function trimNumber(s) {
      while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
      return s;
    }
    
    var s1 = '00123';
    var s2 = '000assa';
    var s3 = 'assa34300';
    var s4 = 'ssa';
    var s5 = '121212000';
    
    alert(s1 + '=' + trimNumber(s1));
    alert(s2 + '=' + trimNumber(s2));
    alert(s3 + '=' + trimNumber(s3));
    alert(s4 + '=' + trimNumber(s4));
    alert(s5 + '=' + trimNumber(s5));
    // end hiding contents -->
    </script>
    
    0 讨论(0)
  • 2020-11-27 06:59

    Ok a simple solution. The only problem is when the string is "0000.00" result in plain 0. But beside that I think is a cool solution.

    var i = "0000.12";
    var integer = i*1; //here's is the trick...
    console.log(i); //0000.12
    console.log(integer);//0.12
    

    For some cases I think this can work...

    0 讨论(0)
  • 2020-11-27 07:01
    var value= document.getElementById("theTextBoxInQuestion").value;
    var number= parseFloat(value).toFixed(2);
    
    0 讨论(0)
  • 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: <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 ()

    0 讨论(0)
  • 2020-11-27 07:11

    More simplified solution is as below. Check this out!

    var resultString = document.getElementById("theTextBoxInQuestion")
                               .value
                               .replace(/^[0]+/g,"");
    
    0 讨论(0)
提交回复
热议问题