>  기사  >  웹 프론트엔드  >  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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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