Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
988 views
in Technique[技术] by (71.8m points)

regex - Why and I getting: "Invalid regular expression. Uncaught SyntaxError. Invalid escape."?

Im trying to create an html input tag that accepts only numbers entered in 1 of 2 formats, and reject all other input.

I want to accept numbers in these formats only, including requiring the dashes:

1234-12

and

1234-12-12

note: this is not for dates, but rather legal chapter numbers

Everything I am reading about regex says that the following should work, but it isn't.

<input class="form-control"
                       type="text"
                       pattern="^(d{4}-d{2}-d{2})|(d{4}-d{2})$"
                       required />

Devtools Console Error in Chrome:

Pattern attribute value ^(d{4}-d{2}-d{2})|(d{4}-d{2})$ is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^(d{4}-d{2}-d{2})|(d{4}-d{2})$/: Invalid escape

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should not escape the hyphen outside a character class in ES6 regex used with the u flag (the one used by default in pattern regexps in the current versions of Chrome and FF).

Also, the regex in the pattern attribute is anchored by default, remove the redudant ^ and $ and shorten the pattern by using an optional group

pattern="d{4}-d{2}(-d{2})?"

This regex in the HTML5 pattern attribute means:

  • d{4}-d{2} - match 4 digits, -, and then 2 digits from the start of string
  • (-d{2})? - and optionally match a - and then 2 digits at the end of the string.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...