>  기사  >  웹 프론트엔드  >  날짜 형식을 검증하는 동안 JavaScript RegEx가 작동하지 않는 이유는 무엇입니까?

날짜 형식을 검증하는 동안 JavaScript RegEx가 작동하지 않는 이유는 무엇입니까?

DDD
DDD원래의
2024-10-18 13:30:30280검색

Why is a JavaScript RegEx Not Working While Validating Date Format?

JavaScript RegEx Not Working

In a JavaScript code snippet, a regular expression (RegEx) is used to validate the format of a date string ("02/2010"). However, the RegEx test consistently returns false for all input values. Is there an issue with the code?

Answer:

Yes, the issue lies in the construction of the RegEx. When creating a RegEx from a string, it's crucial to double-up the backslashes ("\") to account for the parsing of the string as a JavaScript string constant.

The original RegEx:

var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g");

becomes:

var regEx = new RegExp("^(0[1-9]|1[0-2])\\/\d{4}$", "g");

Alternatively, using RegEx syntax directly eliminates the need for double backslashes:

var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/g;

Explanation:

The RegEx is split into three parts:

  • Start of string: "^"
  • Date format pattern: "(0[1-9]|1[0-2])\/\d{4}$"

    • Two digits (01-09 or 10-12) followed by a slash "/"
    • Four digits representing the year (\d{4})
  • End of string: "$"

The backslashes ensure that the slashes and other characters within the pattern are recognized as part of the RegEx.

위 내용은 날짜 형식을 검증하는 동안 JavaScript RegEx가 작동하지 않는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.