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
  • 101,669
  • 28
  • 188
  • 178
Haren Sarma
  • 2,267
  • 6
  • 43
  • 72

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
  • 204,599
  • 20
  • 195
  • 236
2

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
  • 387
  • 1
  • 7
  • 20