除去字符串中的数字以外的所有内容 [英] Removing everything except numbers in a string

查看:204
本文介绍了除去字符串中的数字以外的所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中制作了一个小型计算器,用户输入他们想要借入的利率和金额,并计算他们可能获得多少奖励。

I've made a small calculator in javascript where users enter the interest rate and amount the they want to borrow, and it calculates how much of an incentive they might get.

问题是我担心用户会输入符号,例如

The problem is that I'm worried users will enter symbols, e.g.


贷款金额:£360,000 - 利率:4.6%

Loan amount: £360,000 - Interest Rate: 4.6%

我不担心小数位,因为这些都是需要的,似乎不会影响计算,它是像£和%这样的符号,这些符号会让事情变得混乱。

I'm not worried about the decimal places as these are needed and don't seem to affect the calculation, it's the symbols like £ and % which mess things up.

是否有一种简单的方法可以从代码中删除这些符号:

Is there a simple way to strip out these symbols from the code:

<td><input type="text" name="loan_amt" style="background-color:#FFF380;"></td>
<td><input type="text" name="interest_rate" style="background-color:#FFF380;"></td>


function Calculate()
{
    var loan_amt = document.getElementById('loan_amt').value;
    //this is how i get the loan amount entered
    var interest_rate = document.getElementById('interest_rate').value; 
    //this is how i get the interest rate

    alert (interest_rate);
}


推荐答案

请注意,您应该使用正确的DOM id通过getElementById引用;
您可以使用 .replace()方法:

Note that you should use correct DOM id to refer via getElementById; You can use .replace() method for that:

var loan_amt = document.getElementById('loan_amt');
loan_amt.value = loan_amt.value.replace(/[^0-9]/, '');

但这也将删除浮点分隔符。我认为这是你问题的答案,但不是你问题的解决方案。要将用户输入解析为数字,您可以使用 parseFloat() - 我认为这样会更正确。

But that will remove float point delimiter too. I think it is an answer to you question, but not a solution of your problem. To parse user input as a number, you can use parseFloat() - I think that will be more correct.

这篇关于除去字符串中的数字以外的所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆