ホームページ > 記事 > ウェブフロントエンド > 日付形式の検証中に JavaScript RegEx が機能しないのはなぜですか?
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:
Date format pattern: "(0[1-9]|1[0-2])\/\d{4}$"
The backslashes ensure that the slashes and other characters within the pattern are recognized as part of the RegEx.
以上が日付形式の検証中に JavaScript RegEx が機能しないのはなぜですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。