Copy into text box but remove spaces/commas/formatting/signs (Javascript)

Thug
Soldato
Joined
4 Jan 2013
Posts
3,783
Per title, I'm looking to make a small little feature which would allow people to paste in two separate boxes some numbers. There is a calculation that is run when a button is clicked.

I'm using a bit of HTML/Javascript, but I'm running into an issue.

If number goes in like 1000 then it is fine. If the number is put in like 1,000 (or there is a space or a CCY sign) then it returns NaN which is less than useful....

Anyone got a way around this? Thanks.
 
Have a look at isNaN to validate numbers in textbox, otherwise you will need to write a parser to remove any commas, spaces or other chars.
 
You can use a regex in javascript to remove any non-numeric characters:

myString = myString.replace(/\D/g,'');

You could execute this on your values when the calculation button is clicked.
 
Just be aware that if you're working with floating point numbers that will remove the '.' too. Try:

Code:
var number = parseFloat(yourValue.replace(/[^\d.]/g, '');


You may also need to add '-' to the capturing group if you want to allow negative numbers.
 
Back
Top Bottom