View Full Version : Reg Expr to allow numbers only

Gary Williams
01-16-2004, 05:26 PM
Hi All,

I have been reading regular expression tutorials all afternoon and I cannot get the hang of these things. I'm missing something fundamental in the syntax. However, some months ago, one of the good guys on the board gave me the following reg ex:

onblur="this.value = this.value.replace(/ /g,'').replace( /^(.{2,4})(.{3})(.*)$/, '$1 $2' )"

With this, you can automatically add the space to a UK post code, so if someone enters "SS75TE", the onblur feature changes this post code to "SS7 5TE".

So far, so good.

I now need to ensure that a currency field is converted into numbers only, so, if someone enters:


The onblur will change it to:


Can someone please give me the reg ex to do this (and a brief idiots explanation would be very useful :)) )



01-16-2004, 05:50 PM
You could do a replace like this:
onblur="this.value=this.value.replace(/\D/g,'');"/D means any character but a digit, and you replace those characters with an empty string.

Gary Williams
01-16-2004, 06:00 PM
Hi Liorean,

Thanks, that works fine and gets rid of and , and .

I can actually follow what is happening. Now, if I enter:


I now get


How do I get rid of the 2 digits (98) after the decimal point before removing the decimal point itself?



01-16-2004, 06:09 PM
Do this first:
replace(/\.\d*$/, '')It removes a fullstop, followed by zero or more digits, followed by the end of the string.

Gary Williams
01-16-2004, 06:24 PM
Hi Liorean,

Yes! That did it, the following reg ex works AND I can follow the logic.

Many thanks


onblur="this.value=this.value.replace(/\.\d*$/, '').replace(/\D/g,'');"