我正在创建一个 npm 模块,它将是来自 http://html5pattern.com/ 的正则表达式验证模式的集合。和其他来源。
当我尝试测试一些表达式时,我的问题出现了。我正在使用 Ava.js做简单的断言。
在内部,当测试正则表达式时,Ava 使用 RegEx test()
方法。因此,例如,/[a-zA-Z0-9]+/.test("Us3rN@m3")
将返回 true
。
但是,当您实际使用 /[a-zA-Z0-9]+/
作为输入元素模式属性的正则表达式时,"Us3rN@m3"
返回 false
。
所以我猜测 input 元素在内部进行不同的测试?
HTML spec声明给定的正则表达式编译为 JavaScript 正则表达式,仅指定了“u”标志,这并没有告诉我太多信息。
如果我像这样写正则表达式 /^[a-zA-Z0-9]+$/.test("Us3rNm3")
,它返回 true
就像输入元素一样,但我不确定它在内部是不是这样工作的?
最佳答案
要正确测试 HTML5 模式,请确保用 ^(?:
和 )$
包裹整个字符串模式,以确保整个字符串匹配。
根据 pattern
attribute documentation :
This regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a
^(?:
at the start of the pattern and a)$
at the end).
关于javascript - 输入元素如何检查字符串是否匹配模式属性中指定的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54023331/