日期:2014-05-16  浏览次数:20646 次

写了个最简单的正则表达式 遇到问题 请各位高手帮忙
代码如下:
<script   language= "javascript "   type= "text/javascript ">
function   check(){

var   pattern   =   new   RegExp( "/\d{2}/ ");
var   obj   =   document.getElementById( 'textfield ');

if(   pattern.test(   obj.value   )   ){
alert( 'true ');
obj.focus();
}else{
alert( 'false ');
obj.focus();
}
}
</script>
</head>

<body>
<form   id= "form1 "   name= "form1 "   method= "post "   action= " ">
    <input   type= "text "   name= "textfield "   id= "textfield "   />
    <input   type= "button "   name= "Submit "   value= "提交 "   onclick= "javascript:   check(); "   />
</form>
</body>
</html>

在文本框输入12,弹出框显示的是“false“这是为什么啊?

------解决方案--------------------
var pattern = new RegExp( "/\d{2}/ ");
改成
var pattern = new RegExp(/\d{2}/);
不要加引号
------解决方案--------------------
var pattern = new RegExp( "/\d{2}/ ");--> var pattern = new RegExp(/\d{2}/);
------解决方案--------------------
<script language= "javascript " type= "text/javascript ">
function check(){

var pattern = new RegExp( "\\d{2} ");
alert(pattern)
var obj = document.getElementById( 'textfield ');

if( pattern.test( obj.value ) ){
alert( 'true ');
obj.focus();
}else{
alert( 'false ');
obj.focus();
}
}
</script>