|
-
Feb 25th, 2010, 04:58 PM
#1
Thread Starter
Hyperactive Member
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
-
Feb 25th, 2010, 05:24 PM
#2
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.
-
Feb 25th, 2010, 08:58 PM
#3
Re: Javascript regex question
Code:
foo.replace(/[^\d\.]/g, '').replace(/([\d]*)([\.]?)([\d]*)([\.\d]*)/g, '$1$2$3')
Not too great...
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|