模式 HTML/Javascript 中的无效转义 [英] invalid escape in pattern HTML/Javascript

查看:38
本文介绍了模式 HTML/Javascript 中的无效转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 字段,该字段使用模式来检查输入是否为有效的 Windows 文件路径.

I am trying to make an <input> field that uses a pattern to check if the input is a valid windows file path.

我的模式是

/^(?:[w]:|\)(\[a-zA-Z_-s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$/g

但是,当将其放入 字段的模式属性时:

However, when putting this into the pattern attribute of an <input> field:

<input id="path" type="text" pattern="^(?:[w]:|)([a-zA-Z_-s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$">

控制台显示错误:

Pattern attribute value
^(?:[w]:|\)(\[a-zA-Z_-s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$ is
not a valid regular expression:  Uncaught SyntaxError: Invalid regular
expression: /^(?:[w]:|\)(\[a-zA-Z_-s0-9.()~!@#$%^&=+';,{}[]]+)+.(exe)$/:
Invalid escape

我尝试了多种编写此模式的方法,但似乎都不起作用.

I have tried several ways of writing this pattern, but none seem to work.

推荐答案

你只需要对字符类中必须转义的字符进行转义,否则会一直报这个错误.

You only need to escape the characters in the character class that must be escaped otherwise, you will always get this error.

使用

pattern="(?:w:|\)(\[ws.()~!@#$%^&=+';,{}[]-]+)+.exe"

参见 JSFiddle

详情:

  • 连字符必须在字符类的末尾
  • 必须对字符类中的]进行转义
  • [. 不得转义
  • : 永远不能被转义,它永远不是一个特殊字符
  • [a-zA-Z0-9_] = w
  • pattern 总是默认锚定的,你不需要 ^$ 锚点.
  • The hyphen must be at the end of the character class
  • The ] inside the character class must be escaped
  • The [ and . must not be escaped
  • The : must never be esacaped, it is never a special character
  • [a-zA-Z0-9_] = w
  • The pattern is always anchored by default, you need no ^ and $ anchors.

这篇关于模式 HTML/Javascript 中的无效转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆