很多基础都不是太清楚,从今天开始把基础夯实。
昨天写代码用到了test(),知道这是正则表达式对象的一个方法,但是记得不是太清楚,总结一下
语法:
regexObj.test(str)
参数是一个字符串类型的值,The test()
method executes a search for a match between a regular expression and a specified string. Returns true
or false
.这是MDN上的解释,返回true或者false,如果匹配返回true,否则返回false。
还有一个是获取到input里的输入的值,这个值就是字符串类型,可以作为test()的参数。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- 引入angular文件 -->
<script type="text/javascript" src="https://cdn.bootcss.com/angular.js/1.5.1/angular.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/angular.js/1.5.0-beta.1/angular-route.min.js"></script>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<label for="#email">请输入邮箱</label><input type="text" id="email">
<input type="button" value="按钮" class="btn">
</form>
</body>
<script type="text/javascript">
var emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
$(".btn").click(function(){
var t = $("#email").val();
var isReg = emailReg.test(t);
if(isReg == true){
alert("true");
}else{
alert("false");
}
});
</script>
</html>
这是例子。