javascript: html5-pattern regex question
When I run this script with "\d+"
as pattern value, the regex doesn't work as I expected.
When I escape the backslash it works.
Is the backslash the only character that I have to escape?
<!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">
开发者_如何学C <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>
You have to escape the backslash character in a string used as a RegEx expression just as you would in any JavaScript string.
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";
https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#Escaping_Characters
the back slash must be escaped as part of the strings syntax.
精彩评论