JavaScript: \\d{4} RegExp allows more than 4 digits [duplicate]

醉酒当歌 提交于 2019-12-13 22:21:18

问题


Have following validation for year value from text input:

if (!year.match(new RegExp('\\d{4}'))){
    ...
}

RegExp equals null if numeric of digits from 0 to 3. It's OK.
In case 4 digits it returns value.It's OK.
In case more than 4 digits it returns value again,that it's NOT OK.

Documentation says {n} declaration means exact number,but works like:

exact+

With such ugly validation it work's fine:

if (!year.match(new RegExp('\\d{4}')) || year.length>4){
...
}

I wish to utilize RegExp object only.


回答1:


Yes it would allow more than 4 digits since it would be a partial match use the ^ and $ to mark the beginning and the end of the string.

if (!year.match(new RegExp('^\\d{4}$'))){
    ...
}



回答2:


If you include ^ in your regex it matches the beginning of the string, while $ matches the end, so all up:

^\d{4}$

Will match only against beginning-of-string plus four digits plus end-of-string.

Note that regex literal syntax is generally a bit simpler than saying new Regex():

/^\d{4}$/
// is the equivalent of
new RegExp('^\\d{4}$')

Note that in the literal syntax you don't have to escape backslashes like with the string you pass to the new RegExp(). The forward slashes are not part of the expression itself, you can think of them like quotation marks for regexes.

Also, if you just want to check if a string matches a pattern (yes or no) without extracting what actually matched you should use the .test() method as follows:

if (!/^\d{4}$/.test(year)) {
   ...
}



回答3:


It's matching the first four digits and then the fact that there's any remaining digits it neither here nor there. You need to change your regex so it stops after these four digits, say, by using the string termination anchors:

^\d{4}$



回答4:


Try instead:

'^\\d{4}$'

What you had will match anything with 4 digits anywhere, such as asd1234asd or 123456789



来源:https://stackoverflow.com/questions/8614215/javascript-d4-regexp-allows-more-than-4-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!