2

How can I remove all text characters (not numbers or float) from a javascript variable ?

function deduct(){
    var getamt= document.getElementById('cf').value; //eg: "Amount is 1000"
    var value1 = 100;
    var getamt2 = (value1-getamt);
    document.getElementById('rf').value=getamt2;
}

I want getamt as number. parseInt is giving NaN result.

David Sherret
  • 92,051
  • 24
  • 178
  • 169
Haren Sarma
  • 1,848
  • 3
  • 34
  • 56

2 Answers2

5

You can replace the non-numbers

    var str = "Amount is 1000";
    var num = +str.replace(/[^0-9.]/g,"");
    console.log(num);

or you can match the number

    var str = "Amount is 1000";
    var match = str.match(/([0-9.])+/,"");
    var num = match ? +match[0] : 0;
    console.log(num);

The match could be more specific too

epascarello
  • 195,511
  • 20
  • 184
  • 225
3

Use regular expression like this:

var getamt= document.getElementById('cf').value; //eg: Amount is 1000
var value1 = 100;
var getamt2 = value1 - getamt.replace( /\D+/g, ''); // this replaces all non-number characters in the string with nothing.
console.log(getamt2);

Try this Fiddle

Johny
  • 379
  • 1
  • 6
  • 19