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???
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, eg
"1234".match(/\d{3}$/g) // ["234"]
使用一个^ [0-9] {3} $或^ \\ d {3} $。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.