Bodo Hombah
Bodo Hombah

Reputation: 209

Regular expression to match a number range in JavaScript

I'm having problem with JavaScript regular expressions. I want to match real numbers form 1 to 5. Precission is in two digits. My code is but it doesnt work.

function validate_prosjek(nmb)
{
    var pattern= new RegExp(/[1-4]\.[0-9][0-9]|5\.00/);

    return pattern.test(nmb);
}

It recognizes real numbers higher than 5.

Upvotes: 0

Views: 5505

Answers (1)

Alnitak
Alnitak

Reputation: 340045

You need to "anchor" your regexp with ^ and $ to match the beginning and end of the string, respectively:

var pattern = /^([1-4]\.[0-9][0-9]|5\.00)$/;

You also need to escape the . because it's a special character in regexps, and there's no need to call new RegExp if the regexp is already in /.../ synax.

Upvotes: 2

Related Questions