首頁 > web前端 > js教程 > 主體

為什麼我的正規表示式在 JavaScript 中失敗:揭開反斜線之謎

DDD
發布: 2024-10-18 13:32:02
原創
191 人瀏覽過

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中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板