One: Application examples of regular expressions in JavaScript:
For example, when the front-end interface submits a form, the content of the input box in the form needs to be verified. If the input rules are met, the verification is successful, and the form is submitted; if the input rules are not met, the verification is unsuccessful, and a related error message is displayed.
Regular expressions are often used to verify this requirement ;
index.html:
(1) When defining the regular expression object in JavaScript: var regex1 = /^[\u4e00-\u9fa5]{2,8}$/; That is, it is defined in the middle of the two slashes, and a variable is used to receive it ;
(2) The test() method of the regular expression object in JavaScript is used to verify whether the string complies with the regular expression verification rules;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="#" method="post" id="frmInfo">
<div id="err" style="color:red">
</div>
<div>
姓名:<input id="name" name="name" />
</div>
<div>
身份证:<input id="idNo" name="idNo" />
</div>
<div>
<input type="submit"/>
</div>
</form>
<script type="text/javascript">
document.getElementById("frmInfo").onsubmit = function(){
//在JavaScript中定义的正则表达式对象,只需要在两个斜杠中间书写正则表达式后,就能在JavaScript中获得一个正则表达式对象,
// 然后用一个变量去接受就可以了;
var regex1 = /^[\u4e00-\u9fa5]{2,8}$/; // 校验姓名的正则表达时
var regex2 = /^[1234568]\d{16}[0-9xX]$/;// /^[1234568]\d{16}[\dxX]$/这样写,经过实测也是可以的哦
var name = document.getElementById("name").value;
var idNo = document.getElementById("idNo").value;
if(regex1.test(name) == false){// JavaScript的正则表达式对象提供了test()方法,返回值为true(匹配)或false(不匹配);
document.getElementById("err").innerHTML = "无效姓名";
return false;
}else if(regex2.test(idNo) == false){
document.getElementById("err").innerHTML = "无效idNo";
return false;
}
else{
return true;
}
}
</script>
</body>
</html>
Above, the name and id are verified, like this step by step one by one. When doing projects before, this structure of if else judgment was adopted. This structure can be a good location for positioning. An error in an input box is convenient for pop-up prompts;
effect:
In fact, fortunately, when checking the input box in JavaScript, it should be plug and play, and the attitude of using it as you want should be fine~~~
Then, the application of regular expressions in JavaScript must have many other aspects, follow-up additions...
Then, the form input item verification work is generally used to be handed over to the front-end to solve it?