javascript 如何从变量中删除所有非数字字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28634366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove all non-numeric characters from a variable
提问by Haren Sarma
How can I remove all text characters (not numbers or float) from a javascript 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;
}
I want getamt
as number. parseInt
is giving NaN
result.
我要getamt
号码。parseInt
正在给出NaN
结果。
采纳答案by Johny
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);
回答by epascarello
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
比赛也可以更具体