繁体   English   中英

如何从变量中删除所有非数字字符

[英]How to remove all non-numeric characters from a variable

如何从javascript变量中删除所有文本字符(不是数字或浮点数)?

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

我要用getamt作为号码。 parseInt正在给出NaN结果。

您可以替换非数字

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

或者您可以匹配号码

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

比赛也可能更具体

使用如下正则表达式:

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

试试这个小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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