56

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.

The problem is that I'm worried users will enter symbols, e.g.

Loan amount: £360,000 - Interest Rate: 4.6%

I'm not worried about the decimal places as these are needed and don't seem to affect the calculation, it's the symbols like £ and % which mess things up.

Is there a simple way to strip out these symbols from the code:

<td><input type="text" name="loan_amt" style="background-color:#FFF380;"></td>
<td><input type="text" name="interest_rate" style="background-color:#FFF380;"></td>


function Calculate()
{
    var loan_amt = document.getElementById('loan_amt').value;
    //this is how i get the loan amount entered
    var interest_rate = document.getElementById('interest_rate').value; 
    //this is how i get the interest rate

    alert (interest_rate);
}
Joshua Dawson
  • 629
  • 10
  • 17
Reindeer
  • 575
  • 1
  • 4
  • 11
  • 1
    possible duplicate of [Regex to replace everything except numbers and a decimal point](http://stackoverflow.com/questions/4572194/regex-to-replace-everything-except-numbers-and-a-decimal-point) – mplungjan Aug 07 '13 at 09:30
  • A minimum of research is needed when you ask questions here. How could you miss all the other identical questions? – mplungjan Aug 07 '13 at 09:31
  • Your markup is wrong, there is no ID for input – Dhaval Marthak Aug 07 '13 at 09:31
  • You can also remove last character from the input, because % symbol will be in the end always for interest rate input – Dhaval Marthak Aug 07 '13 at 09:33

7 Answers7

60

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.

Community
  • 1
  • 1
Alma Do
  • 37,009
  • 9
  • 76
  • 105
  • 18
    You could use `.replace(/[^0-9.]/g, '');` if you need to include the dot. – Moob Aug 07 '13 at 09:40
  • 3
    No, that is not a good idea since user then can input 1234...56 and that will be treated as a good number – Alma Do Aug 07 '13 at 09:41
  • also does parseFloat() handle different decimal marks? i.e. some countries use `,` and others `.`. – Jake Aitchison Aug 07 '13 at 09:42
  • Sorry I'm quite new to this. I like the idea of parseFLoat but struggling to apply it to my var loan_amt... – Reindeer Aug 07 '13 at 09:54
  • If you are not concerned about illegal characters and just want to extract float value in any case, I suppose you can first replace commas to dots, then remove all non-numbers and non-dots (see comment from @Moob) and then apply parseFloat() - if it executed successfully, that's your number. – Alma Do Aug 07 '13 at 09:57
  • The first bit works really well, .replace(/....however I cant get parseFloat to work with it. Not sure if I'm applying it correctly? parseFloat(loan_amt.value); OR if the problem is that loan_amt.value isn't a string? – Reindeer Aug 07 '13 at 10:16
  • 4
    This solution doesn't work. The accepted answer in this other question does work: http://stackoverflow.com/questions/5663080/regexpr-advice-needed-remove-all-chars-from-string-except-of-numbers-0-9-and – OMA Apr 28 '15 at 18:13
  • Does this work with JSON.stringify? I know it should but something seems to be wrong with the replacement function when it comes to it. – christopherson Mar 10 '19 at 21:57
  • without `/g`It returned `"20/02/1995 "`as `"2002/1995"`. I used `.trim()`to remove the space in the end. – Sabri Meviş Aug 22 '19 at 06:03
41

This is the shortest:

replace(/\D/g,'');
Pinonirvana
  • 920
  • 1
  • 8
  • 12
5

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
JulienRioux
  • 2,853
  • 2
  • 24
  • 37
1

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/

usman allam
  • 274
  • 1
  • 5
1

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.

Moob
  • 14,420
  • 1
  • 34
  • 47
0

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

stema
  • 90,351
  • 20
  • 107
  • 135
Surya Prakash Tumma
  • 2,153
  • 4
  • 27
  • 47
0

Did the function to remove all but floats. Double dot is not possible.

inspired by the solution of JulienRioux

function removeAllButFloatFromInput(input, floatAmount) {
  $(input).on("input change paste", ({ target }) => {
    let { value } = target
    let allowedChars = [".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    let newValArr = value.split("").filter(char => allowedChars.includes(char)).join("").split(".")
    let newValStr = ""

    if (newValArr.length == 1) {
      newValStr = newValArr[0]
    } else if (newValArr.length == 2 && floatAmount !== undefined) {
      newValArr[1] = newValArr[1].substr(0, floatAmount)
      newValStr = newValArr.join(".")
    } else if (newValArr.length == 2) {
      newValStr = newValArr.join(".")
    } else if (floatAmount !== undefined) {
      newValStr = newValArr[0] + "." + newValArr.splice(1).join("").substr(0, floatAmount)
    } else {
      newValStr = newValArr[0] + "." + newValArr.splice(1).join("")
    }

    target.value = newValStr
  })

  if (!!floatAmount) {
    $(input).on("blur", ({ target }) => {
      if (!!target.value) {
        target.value = parseFloat(target.value).toFixed(floatAmount)
      } else {
        target.value = parseFloat(0).toFixed(floatAmount)
      }
    })
  }
}