Removing everything except numbers in a string

JavascriptRegex

Javascript Problem Overview


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);
}

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

This is the shortest:

replace(/\D/g,'');

Solution 3 - Javascript

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

Solution 4 - Javascript

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/

Solution 5 - Javascript

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.

Solution 6 - Javascript

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

Solution 7 - Javascript

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)
      }
    })
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionReindeerView Question on Stackoverflow
Solution 1 - JavascriptAlma DoView Answer on Stackoverflow
Solution 2 - JavascriptPinonirvanaView Answer on Stackoverflow
Solution 3 - JavascriptJulienRiouxView Answer on Stackoverflow
Solution 4 - Javascriptusman allamView Answer on Stackoverflow
Solution 5 - JavascriptMoobView Answer on Stackoverflow
Solution 6 - JavascriptSurya Prakash TummaView Answer on Stackoverflow
Solution 7 - JavascriptDen NikitinView Answer on Stackoverflow