Javascript regex question
I am working on a special calculator and I want a regular expression to remove non-alpha characters and only allow 1 dot.
Here is the function I have so far:
Code:
function stripAlphaChars(pstrSource) {
var m_strOut = new String(pstrSource);
m_strOut = m_strOut.replace(/[^0-9\.]/g, '');
return m_strOut;
}
This code works fine for allowing 0-9 to be typed, but it removes dots.
Can someone help out?
I need to allow 0-9 and 1 single "."
Thanks
Re: Javascript regex question
Not sure if there's a more efficient way, but here's one thought...
Code:
function stripAlphaChars(pstrSource) {
var m_strOut = new String(pstrSource);
m_strOut = m_strOut.replace(/[^0-9\.]/g, '');
var numOfDots = m_strOut.split(".").length-1;
for(i=0;i<numOfDots-1;i++){
m_strOut = m_strOut.replace(/\./, '');
}
return m_strOut;
}
The first replace takes out everything but numbers and dots. numOfDots gets the number of dots in the string. The for loop will do a non-global (replacing only the first instance that it finds) replace of dots until only one (the last) dot is left.
Re: Javascript regex question
Code:
foo.replace(/[^\d\.]/g, '').replace(/([\d]*)([\.]?)([\d]*)([\.\d]*)/g, '$1$2$3')
Not too great...