学习js的过程中,根据知识点编写一些code进行测试,以便检验。
这段程序使用了以下知识点:
1.regexp,对数据进行模式匹配
2.使用location对象进行页面跳转。
3.cookie/localstorage等本地存储的使用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<span id="span1"></span><br/>
<label for="inp1" id="label1">
用户名:<input id="inp1" type="text" placeholder="username">
</label>
<br/>
<label for="inp2" id="label2">
密码:<input id="inp2" type="password" placeholder="password">
</label>
<br/>
<button id="btn1" onclick="jData()">submit</button>
<script type="text/javascript">
var span1=document.getElementById("span1");
var inp1=document.getElementById("inp1");
var inp2=document.getElementById("inp2");
function jData(id){
//校验用户姓名:只能输入1-30个以字母开头的字串
var patt1=new RegExp(/^[a-z][a-zA-Z0-9_-]{0,29}/,"g");
//校验密码:只能输入6-20个字母、数字、下划线
var patt2=new RegExp(/[a-zA-Z0-9_]{6,20}/,"g");
var res=patt1.test(inp1.value)&&patt2.test(inp2.value);
if(res){
// window.location.href="http://www.baidu.com";
window.location.assign("http://www.baidu.com");
// window.event.returnValue = false;
}else{
span1.innerHTML="username or password wrong";
}
}
</script>
</body>
</html>
1.正则表达式(参考,http://w3school.com.cn/jsref/jsref_obj_regexp.asp)
1)应用场景
对指定内容进行模式匹配,通过模式匹配查找、替换、删除、修改对应的内容或进行提交验证
2)语法。
a.[]和元数据
1)[字符] 理解为对方括号具体内容匹配
2). , \w ,\d, 理解为对某一类进行通配
b.量词
n+;至少一次(一次及以上)
n*;任意次
n?;0次或1次
n{};这种指定具体次数:n{x};x次
n{x,y}次数在x~y之间即可
n{x,}至少x次(x次及以上)
^n;以n为开头
n$;以n结尾
3)实例。
3-1)为了保证页面输出安全,我们经常需要对一些特殊的字符进行转义,请写一个函数escapeHtml,将<, >, &, “进行转义
<script>
function escapeHtml(str){
return str.replace(/[<>"&]/g, function (match) {
switch (match){
case "<":
return "<";
case ">":
return ">";
case '\"':
return """;
case "&":
return "&";
}
})
}
var str="<p>this is a test &";
console.log(escapeHtml(str));
console.log(str);
</script>
3-2)提交验证。
浙公网安备 33010602011771号