[英]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.