admin管理员组

文章数量:1025208

I am trying to write a regular expression which returns a three digit integer only. Not less than three or more than three. However my regex below is also true for four digit numbers. Am i missing something?

var threeDigits = /\d{3}$/

console.log(threeDigits.test("12"))// false
console.log(threeDigits.test("123"))// true
console.log(threeDigits.test("1234"))// true yet this is four digits???

I am trying to write a regular expression which returns a three digit integer only. Not less than three or more than three. However my regex below is also true for four digit numbers. Am i missing something?

var threeDigits = /\d{3}$/

console.log(threeDigits.test("12"))// false
console.log(threeDigits.test("123"))// true
console.log(threeDigits.test("1234"))// true yet this is four digits???
Share Improve this question asked May 17, 2017 at 17:01 ochieng benjaochieng benja 791 silver badge8 bronze badges 1
  • You should use ^\d{3}$ where ^ is for start of string. – Sahil Gulati Commented May 17, 2017 at 17:02
Add a ment  | 

2 Answers 2

Reset to default 6

You have the ending anchor $, but not the starting anchor ^:

var threeDigits = /^\d{3}$/

Without the anchor, the match can start anywhere in the string, e.g.

"1234".match(/\d{3}$/g)  // ["234"]

Use either one ^[0-9]{3}$ or ^\d{3}$ .

I am trying to write a regular expression which returns a three digit integer only. Not less than three or more than three. However my regex below is also true for four digit numbers. Am i missing something?

var threeDigits = /\d{3}$/

console.log(threeDigits.test("12"))// false
console.log(threeDigits.test("123"))// true
console.log(threeDigits.test("1234"))// true yet this is four digits???

I am trying to write a regular expression which returns a three digit integer only. Not less than three or more than three. However my regex below is also true for four digit numbers. Am i missing something?

var threeDigits = /\d{3}$/

console.log(threeDigits.test("12"))// false
console.log(threeDigits.test("123"))// true
console.log(threeDigits.test("1234"))// true yet this is four digits???
Share Improve this question asked May 17, 2017 at 17:01 ochieng benjaochieng benja 791 silver badge8 bronze badges 1
  • You should use ^\d{3}$ where ^ is for start of string. – Sahil Gulati Commented May 17, 2017 at 17:02
Add a ment  | 

2 Answers 2

Reset to default 6

You have the ending anchor $, but not the starting anchor ^:

var threeDigits = /^\d{3}$/

Without the anchor, the match can start anywhere in the string, e.g.

"1234".match(/\d{3}$/g)  // ["234"]

Use either one ^[0-9]{3}$ or ^\d{3}$ .

本文标签: javascriptRegular expression to match specific number of digitsStack Overflow