当我使用 "\d+"
作为模式值运行此脚本时,正则表达式无法按我的预期工作。
当我转义反斜杠时它就起作用了。
反斜杠是我必须转义的唯一字符吗?
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Enter a number:</p>
<form id="form">
<script type="text/javascript">
var form = document.getElementById( 'form' );
var input = document.createElement( 'input' );
input.name = 'amount';
input.type = 'number';
input.pattern = "\\d+";
form.appendChild( input );
</script>
<br /><br />
<input type="submit" value="OK"/>
</form>
</body>
</html>
最佳答案
您必须转义用作 RegEx 表达式的字符串中的反斜杠字符,就像在任何 JavaScript 字符串中一样。
To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:
var home = "c:\\temp";
关于javascript:html5 模式正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7216256/