简体   繁体   中英

How to remove all non-numeric characters from a variable

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM