Coding Tips (JavaScript/CSS/VBA/Win32)

Useful code snippets, tips and some Windows applications
Use ProxyChanger 2.2

to change IE proxy settings

The regexp number pattern for JavaScript

This pattern supports optional decimals and the minus sign. First of all, let me remind you of some basic special pattern matching characters:

^ - matches the beginning of the string

$ - matches the end of the string

? - matches 0 or 1 of the previous character or a group of characters

+ matches at least 1 of the previous character or a group of characters

* - matches the previous character or a group of characters any number of times.

Our task is to write a pattern to determine whether a string is a number using a regular expression.

We want out pattern to flexible and allow for different formats.

Let's start with a simple one.

re = /\d+/;

\d represents any digit, and + will match at least one digit or more.

This pattern will match any integer number., e.g 500. However, it will also match "as 500 units";

To match numbers only, we need to use delimiters, ^ and $ for the beginning and end of the string.

The new regexp pattern will be as follows: /^\d+$/;

Now it will match numbers only.

What about decimal fractions? To ensure support for decimal fractions, let's add the following: \.\d+

\. represents a period.

The new regexp pattern will look like this:

re = /^\d+\.\d+$/;

This matches 100.1 but does not match 100. We do want to allow both, don't we?

Let's use the parenthesis around the decimal part and make it optional by using the ? quantifier (once or not at all).

re = /^\d+(\.\d+)?$/;

Now this regexp pattern will work both with integer and floating numbers.

Is that all? I think we forgot about negative numbers.

Let's add an optional minus in front: -?

The final expression looks as follows:

re = /^-?\d+(\.\d+)?$/;

Regexp reference at Regular-Expressions.info