SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2002
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regular Expressions and adding numbers in a string

    Hey all - I've been playing with regular expressions lately and I must say they confuse me like all heck but I'm sure once they click I won't know how I lived without them.

    I've done some little ones in PHP but I"m working in Javascript today trying to take a string and strip out all the numbers and add them up. This will eventually be used in onBlur but I'm just trying to figure out the basics to it.

    The string is basically a comma delimited listing of "text #, text ##, text ##, text #" etc. The number can be one or two digits. I want to be able to match the one or two digit numbers than add them up.

    Can anyone point me in the right direction of how to get started? I've got this pattern that seems to do the trick but I can't get it to work

    \d(\d)?(\d)?

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,875
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    This one might work a bit better

    /(\d{1,2})/g
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you want to exclude returning parts of numbers with more than 2 digits
    you'll need to be more specific-


    var Rx= /^|\D(\d{1,2})(?!\d)/g;
    var s='bob is 122, tom is 4, jack is 15';
    alert(eval(s.match(Rx).join('+')));


    // or using exec:

    Code:
    function total1or2digits(s){
    	var Rx= /(^|\D)(\d{1,2})(?!\d)/g, M, T= 0;
    	while((M= Rx.exec(s)) != null) T+= (+M[2]);
    	return  T;
    }
    alert(total1or2digits(s))

  4. #4
    SitePoint Enthusiast
    Join Date
    Jan 2002
    Posts
    48
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That function worked out perfect mrhoo. The regex felgall gave will work as well. I got it working with the inputs I needed. Thanks again for your help.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •