Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for maximum length in JavaScript

How can I limit the length of a string matching a RegEx

I assumed that var sixCharsRegEx = /^.{6,7}/ would only match strings of lengths 6 or 7

but no: http://jsfiddle.net/FEXbB/

What am I missing?

like image 983
EasierSaidThanDone Avatar asked Jul 16 '12 19:07

EasierSaidThanDone


People also ask

How long can text be in a regular expression?

The following regular expression ensures that text is between 1 and 10 characters long, and additionally limits the text to the uppercase letters A–Z. You can modify the regular expression to allow any minimum or maximum text length, or allow characters other than A–Z.

How many characters can be in a regular expression?

The following regular expression ensures that text is between 1 and 10 characters long, and additionally limits the text to the uppercase letters A–Z. You can modify the regular expression to allow any minimum or maximum text length, or allow characters other than A–Z.

How do you check the length of a string in JavaScript?

For example, JavaScript strings have a length property that holds an integer indicating the string’s length. However, using regular expressions to check text length can be useful in some situations, particularly when length is only one of multiple rules that determine whether the subject text fits the desired pattern.

How do I use the second regex in JavaScript without xregexp?

Standard JavaScript without XRegExp doesn’t have a “dot matches line breaks” option, so the second regex uses a character class that matches any character. See Any character including line breaks for more information. The following regex matches any string that contains between 10 and 100 nonwhitespace characters:


2 Answers

You are missing closing dollar at the end. Correct one is: /^.{6,7}$/

like image 104
Arkadiusz 'flies' Rzadkowolski Avatar answered Sep 18 '22 15:09

Arkadiusz 'flies' Rzadkowolski


Match the start and the end.

var sixCharsRegEx = /^.{6,7}$/; 

Your improved example

like image 31
Madara's Ghost Avatar answered Sep 22 '22 15:09

Madara's Ghost