Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

javascript - Removing everything except numbers in a string

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.

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...