62403

Regular expression to match a number range in JavaScript

Question:

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.

Answer1:

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.

Recommend

  • Password strong - not require each condition
  • Does Perl currently (5.8 and 5.10) make any promises about the order alternations will be used?
  • Parsing tokens with PLY
  • writing unicode to binary file in python
  • TextPad “find in files” not matching on simple OR regex
  • How can I get new CSRF token in LARAVEL by using ajax
  • regex question for removal of javascript malware
  • MVC - Dynamically loading Partial Views
  • str_replace with line break? [closed]
  • Notepad++ - delete all lines with certain text
  • ProgressBar Paint Method?
  • Get XML response value with GDataXML
  • opengl window freezing during move/resize
  • Rails redirect_to another controller method throwing “Template missing”
  • cd command not working with execvp
  • How to access recipient on sent messages page with mailboxer
  • Raphael.js function getBBox give back NAN/NAN/NAN in IE8
  • matching similar elements in between two lists
  • IE10 strips out hashtag from the URL
  • Create a link to a web page that runs a Javascript function on the page
  • Problems with toDataURL HTML5 other ways to get canvas data?
  • Find JSON nested nodes using multiple string values
  • Is it possible to define rest argument in OCaml?
  • Python cosine function precision [duplicate]
  • Calculate time difference in hh:mm:ss with simple javascript/jquery
  • Eliminate partial duplicate rows from result set
  • Is it possible to access block's scope in method?
  • R: gsub and capture
  • jqPlot EnhancedLegendRenderer plugin does not toggle series for Pie charts
  • Transpose CSV data with awk (pivot transformation)
  • Comma separated Values
  • Buffer size for converting unsigned long to string
  • Acquiring multiple attributes from .xml file in c#
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • How can I remove ASP.NET Designer.cs files?
  • Binding checkboxes to object values in AngularJs
  • java string with new operator and a literal
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?