«

Oct 23

Match Numbers using RegExp

Since I use JavaScript as one of my primary development languages, I tend to need little helper functions to accomplish small tasks. One in particular I’ve needed more than any other is the ability to match a number, no matter how it was formatted. I found the following RegExp expression that has worked well for me in all my projects. It will match whole numbers (1, 2, 100, etc), decimals (1.01, 3.14, 100.50, etc) and comma formatted numbers (1,001, 10,375.34, 4,368,326.75). Hopefully this helps you as well.

// match a number
function matchNumber(num) {
    var result = /(?:^|\s)([1-9](?:\d*|(?:\d{0,2})(?:,\d{3})*)(?:\.\d*[1-9])?|0?\.\d*[1-9]|0)(?:\s|$)/.test(num);
    return result;
}

Here is a test fiddle I made: http://jsfiddle.net/dLne8219/

Any comments or questions let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>