Results 1 to 3 of 3

Thread: Javascript regex question

  1. #1

    Thread Starter
    Hyperactive Member xxarmoxx's Avatar
    Join Date
    Mar 2007
    Posts
    378

    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

  2. #2
    Frenzied Member
    Join Date
    Apr 2009
    Location
    CA, USA
    Posts
    1,516

    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.

  3. #3
    I'm about to be a PowerPoster!
    Join Date
    Jan 2005
    Location
    Everywhere
    Posts
    13,647

    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
  •  



Click Here to Expand Forum to Full Width