JavaScript 正则表达式使用

来源:互联网 发布:java面试宝典2015 编辑:程序博客网 时间:2024/06/05 10:25

简述:

JavaScript 正则表达式试写,同时熟悉下js的语法


实现:

构造一个输入框,输入一个字符串,点击button后进行正则表达式的匹配


知识点:

1)函数function()的构造和使用

2)页面内传值(输入框传入一个字符串),用getElementById()获取值,进入函数

3)button点击事件触发

4)findelementById() 指定输出

5) javascript循环,if语句,变量声明使用

6)js的数组及遍历的使用


需求:

写一个密码验证,必须是八位不重复的字符,包括大写,小写,数字


代码:

test.html

<!DOCTYPE html><html><head><script type = "text/javascript">function execute(){var inputPwd = document.getElementById('inputPwd').value;var pattern = new RegExp("^[a-zA-Z0-9]{8}");var isMatch = inputPwd.match(pattern);//null to false and not null to trueif(isMatch == null)isMatch = false;elseisMatch = true;if(inputPwd.length != 8)isMatch = false;if(isMatch){for(i = 0;i < 7;i++)for(j = i + 1;j < 8;j++){if(inputPwd[i] == inputPwd[j]){isMatch = false;break;}}}if(isMatch){//judge if contains Capital letter,small letter and numbervar type = new Array(false,false,false);for(i = 0;i < 8;i++){                 if(inputPwd[i] >= 'A' && inputPwd[i] <= 'Z'){                      type[0] = true;} else if(inputPwd[i] >= 'a' && inputPwd[i] <= 'z'){  type[1] = true;} else if(inputPwd[i] >= '0' && inputPwd[i] <= '9'){  type[2] = true;}}for(i = 0;i < 3;i++){if(type[i] == false){isMatch = false;break;}}}if(isMatch == false)document.getElementById('result').innerHTML = 'failure';elsedocument.getElementById('result').innerHTML = 'success';}</script></head><body><B>verify javascript Regular Expression</B><br><br><input type= "text" id = 'inputPwd' value = '' /><input type = 'button' value = "exec" onclick = 'execute()'/><br><br><B>result:<B> <b id = 'result'></b></body></html>

输出:

如果不满足要求,result: failure