EasierSaidThanDone
EasierSaidThanDone

Reputation: 1897

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?

Upvotes: 33

Views: 116426

Answers (4)

burning_LEGION
burning_LEGION

Reputation: 13460

you must use end of string symbol $

like this ^.{6,7}$

Upvotes: 6

Esailija
Esailija

Reputation: 140234

You are missing the end anchor:

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

Upvotes: 5

Madara's Ghost
Madara's Ghost

Reputation: 175098

Match the start and the end.

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

Your improved example

Upvotes: 9

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

Upvotes: 56

Related Questions