Removing everything except numbers in a string

前端 未结 6 944
旧巷少年郎
旧巷少年郎 2020-12-11 14:16

I\'ve made a small calculator in javascript where users enter the interest rate and amount the they want to borrow, and it calculates how much of an incentive they might get

相关标签:
6条回答
  • 2020-12-11 14:53

    This is the shortest:

    replace(/\D/g,'');
    
    0 讨论(0)
  • 2020-12-11 14:57

    there is very good plugin you can use it. For example

    //include jQuery.js and autoNumeric-1.8.3.js javascript files in the header.

        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"> </script>
        <script src="autoNumeric-1.8.0.js" type=text/javascript> </script>
    
      // this example uses the id selector & no options passed    
      jQuery(function($) {
          $('#someID_defaults').autoNumeric('init');    
      });
    

    see check below http://www.decorplanit.com/plugin/

    0 讨论(0)
  • 2020-12-11 15:03

    try this

    Eg:

    var a="4.52%"
    var stringLength = a.length;
    var lastChar = a.charAt(stringLength - 1); 
    
    if(lastChar.match(/[^\w\s]/)) {
        a=a.substring(0,stringLength - 1);
    }
    
    alert(a);
    

    Now you can typecast to number

    0 讨论(0)
  • 2020-12-11 15:09

    Here is my solution:

    const filterNum = (str) => {
      const numericalChar = new Set([ ".",",","0","1","2","3","4","5","6","7","8","9" ]);
      str = str.split("").filter(char => numericalChar.has(char)).join("");
      return str;
    }
    
    console.log(filterNum("143.33$"));
    // 143.33
    
    0 讨论(0)
  • 2020-12-11 15:11

    You should probably test for and reject invalid values but if you have to clean a dodgy string into a number then this should work:

    var inStr = "a12ab.c34...h.re567";
    var justOneDot = inStr.replace(/[.](?=.*?\.)/g, '');//look-ahead to replace all but last dot
    var outStr = parseFloat(justOneDot.replace(/[^0-9.]/g,'')).toFixed(2); //parse as float and round to 2dp 
    // = 1234.57
    

    Play with it in this JS Bin.

    0 讨论(0)
  • 2020-12-11 15:13

    Note that you should use the correct DOM id to refer via getElementById. You can use the .replace() method for that:

    var loan_amt = document.getElementById('loan_amt');
    loan_amt.value = loan_amt.value.replace(/[^0-9]/g, '');
    

    But that will remove float point delimiter too. This is an answer to your question, but not a solution for your problem. To parse the user input as a number, you can use parseFloat() - I think that it will be more appropriate.

    0 讨论(0)
提交回复
热议问题