gpt4 book ai didi

javascript - 为什么这个简单的正则表达式除了 html5 输入模式属性之外在任何地方都可以工作?

转载 作者:行者123 更新时间:2023-12-02 14:44:27 25 4
gpt4 key购买 nike

This HTML input当输入中的值为“1”时,颜色本身为红色,表示模式不匹配。

var inp = document .createElement ('input');
inp .pattern = '^\d+\.?\d*$';
document .getElementById ("foo") .appendChild (inp);

正则表达式 /^\d+\.?\d*$/当我在其他地方测试时匹配“1”。看起来也应该如此。

为什么表单元素匹配失败? (火狐浏览器。)

最佳答案

字符串表示,儿子。

您对模式属性的使用是正确的,因为您使用的是字符串文字。来自 MDN :

The regular expression language is the same as JavaScript's. The pattern is not surrounded by forward slashes.

但是,在字符串文字中,您必须先对 \ 进行转义,然后斜杠才能在字符串文字意义上获得自己的 li'l 解释。如果对它进行转义,它将被视为实际的斜杠,然后整个模式将被 RegExp 引擎识别为特殊字符。

var inp = document.createElement('input');
inp.pattern = '^\\d+\\.?\\d*$';
document.getElementById("foo").appendChild(inp);

https://jsfiddle.net/qatt3rwt/4/

关于javascript - 为什么这个简单的正则表达式除了 html5 输入模式属性之外在任何地方都可以工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36728838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com