ホームページ  >  記事  >  ウェブフロントエンド  >  正規表現が JavaScript で失敗するのはなぜですか: バックスラッシュの謎を解明する

正規表現が JavaScript で失敗するのはなぜですか: バックスラッシュの謎を解明する

DDD
DDDオリジナル
2024-10-18 13:32:02128ブラウズ

Why is My Regular Expression Failing in JavaScript: Unveiling the Backslash Enigma

Regular Expression Not Working in JavaScript: Understanding Backslashes

In the provided code, you attempt to check the validity of a date string using a regular expression. However, the test always returns false, despite the fact that the regular expression appears correct when used in online editors.

The issue lies in your use of backslashes. When creating a regular expression from a string, it is necessary to double-up the backslashes to account for the string parse. In your code:

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

The backslashes in the string are interpreted as escape characters, which prematurely terminate the expression. To fix this, you need to double the backslashes:

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

Alternatively, you can use a JavaScript regular expression syntax to create the pattern, which eliminates the need for the g modifier:

<code class="javascript">var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/;</code>

With the backslashes correctly escaped, the regular expression should now correctly validate the date strings.

以上が正規表現が JavaScript で失敗するのはなぜですか: バックスラッシュの謎を解明するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。