一.正则表达式
1.正则表达式对象
2.正则表达式对象(三个方法)
二.
- 编写计算器,实现加、减、乘、除。
代码:
<body>
请输入第一个数:<input type="text" id="one" /><br>
请输入第二个数:<input type="text" id="two" /><br>
运算符:<input style="background-color: green;" type="button" name="" id="jia" value="+" onclick="cal_l('+')"/>
<input style="background-color: green;" type="button" name="" id="jian" value="-" onclick="cal_l('-')"/>
<input style="background-color: green;" type="button" name="" id="cheng" value="*" onclick="cal_l('*')"/>
<input style="background-color: green;" type="button" name="" id="chu" value="/" onclick="cal_l('/')"/><br>
运算结果是:<input type="text" name="" id="result" value="" />
<script type="text/javascript">
// 创建一个函数cal_l
function cal_l (a){
// 获取第一个输入框内输入的数据
var first = parseInt(document.getElementById("one").value)
// 获取第二个输入框的数据
var secend = parseInt(document.getElementById("two").value)
// 声明一个变量存放运算后的结果
var result
if(a=="+"){
result=parseInt(first)+parseInt(secend)
} else if(a=="-"){
result=parseInt(first)-parseInt(secend)
} else if(a=="*"){
result=parseInt(first)*parseInt(secend)
}else{
result=parseInt(first)/parseInt(secend)
}
document.getElementById("result").value = result
}
</script>
</body>
三.
- 编写注册页面,使用正则表达式完成相关验证,可以使用alert弹出。
代码:
<body>
<b>欢迎注册**网站<b><br>
姓名:<input type="text" placeholder="2-4个中文" name="" id="names" value="" /><br>
密码:<input type="text" placeholder="至少六位只能数字字母下划线" name="" id="password" value="" /><br>
邮箱:<input type="text" placeholder="单域名邮箱" name="" id="emily" value="" /><br>
年龄:<input type="text" placeholder="整数" name="" id="age" value="" /><br>
<input type="button" name="" id="bt" value="验证信息" />
<script type="text/javascript">
document.getElementById("bt").onclick = function(){
var nam = document.getElementById("names").value
var name =/^[\u4e00-\u9fa5]{2,4}$/
var isname = name.test(nam)
if (isname==false){
alert("用户名不对")
return
}
var password = document.getElementById("password").value
var pass = /^[0-9a-zA-Z_]{6,}$/
var ispass = pass.test(password)
if (ispass==false){
alert("密码格式不对")
return
}
var eml = document.getElementById("emily").value
var emls = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
var iseml = emls.test(eml)
if (iseml==false){
alert("邮箱域名格式不对")
return
}
var age = document.getElementById("age").value
var ages = /^[0-9]*$/
var isage = ages.test(age)
if (isage==false){
alert("年龄格式不对")
return
}
}
</script>
</body>