JavaScript中使用正则表达式
Posted liudemeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript中使用正则表达式相关的知识,希望对你有一定的参考价值。
创建正则对象
-
RegExp 对象是带有预定义属性和方法的正则表达式对象。 方式一:
var reg = new RegExp("\d", ‘i‘);
方式二:
var reg = /\d/i;
参数
标志 | 说明 |
---|---|
i | 忽略大小写 |
g | 全局匹配 |
gi | 全局匹配+忽略大小写 |
正则匹配
-
test() 是一个正则表达式方法。
-
它通过模式来搜索字符串,然后根据结果返回 true 或 false。
// 匹配日期
var dateStr = "2019-09-10";
var reg = /^\d4-\d2-\d2$/;
console.log(reg.test(dateStr));
匹配正则表达式
console.log(/\d/.test("998"));//true
console.log(/\d*/.test("998"));//true
console.log(/\d+/.test("998"));//true
console.log(/\d0,/.test("998"));//true
console.log(/\d2,3/.test("998"));//true
console.log(/\D/.test("eat"));//true
console.log(/\s/.test(" "));//true
console.log(/\S/.test("嘎嘎"));//true
console.log(/\w/.test("_"));//true
console.log(/\W/.test("_"));//true
正则表达式案例
-
验证ip地址
-
验证密码强弱
-
验证手机号是否合法
var ipStr = "192.168.102.103";
var reg = /^(\d1,2|1\d\d|2[0-4]\d|25[0-5])\.(\d1,2|1\d\d|2[0-4]\d|25[0-5])\.(\d1,2|1\d\d|2[0-4]\d|25[0-5])\.(\d1,2|1\d\d|2[0-4]\d|25[0-5])$/;
console.log(reg.test(ipStr))
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>passwordCheck</title>
<script type="text/javascript" src="Js/jquery1.6.1.js"></script>
<script type="text/javascript">
$(function()
$(‘#pwd‘).keyup(function()
var val = $(this).val();
isDigit(val);
);
function isDigit(s)
var pattern_d = /^\d+$/; //全数字
var pattern_s = /^[A-Za-z]+$/ //全字符
var pattern_w = /^\w+$/; //数字或者字符
var pattern_W = /^\W+$/ //全非数字也非字符
var pattern_r = /^\w+\W+[\w\W]*\w+$/ //以字母或者数字开头结尾的字符串
var html = ‘‘;
var x = 0;
var y = 0;
$(‘#user‘).html(s);
if(pattern_W.exec(s))
html += ‘非数字也非字符<br />‘;
x = 0;
y = 0;
if(pattern_w.exec(s))
html += ‘数字或者字符<br />‘;
y = 1;
if(pattern_d.exec(s))
html += ‘全数字<br />‘;
x = 1;
y = 0;
if(pattern_s.exec(s))
html += ‘全字符<br />‘;
x = 2;
y = 0;
if(pattern_r.exec(s))
html += ‘以字母或者数字开头结尾的字符串<br />‘;
x = 3;
y = 2;
if( y === 0 && x === 0)
html += ‘密码格式错误<br />‘;
if( x > 0 && y === 0)
html += ‘安全级别《低》<br />‘;
if( x === 0 && y === 1)
html += ‘安全级别《中》<br />‘;
if( y === 2)
html += ‘安全级别《高》<br />‘;
html += x + ‘<br />‘ + y;
$(‘#password‘).html(html);
;
);
</script>
</head>
<body>
<form action="#" method="#">
用户名:<input type="text" name="" /><span id="user"></span><br />
密码:<input type="password" name="" id="pwd" /><span id="password"></span><br />
</form>
</body>
</html>
var phoneNumStr = "15897808512";
var reg = /^1[3456789]\d9$/;
console.log(reg.test(phoneNumStr));
正则提取
search
-
方法使用表达式来搜索匹配,然后返回匹配的位置。
var str = "Visit W3School!";
var n = str.search("W3School");
// var n = str.search(/W3School/);
console.log(n)
match
-
方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。
var peopleStr = "张三:1000, 李四:5000, 王五:8000"; var array = peopleStr.match(/\d+/g); console.log(array);
分组
var dateStr = ‘2016-1-5‘; // 正则表达式中的()作为分组来使用,获取分组匹配到的结果用Regex.$1 $2 $3....来获取 var reg = /(\d4)-\d1,2-\d1,2/; if (reg.test(dateStr)) console.log(RegExp.$1);
正则替换
replace替换与正则表达式匹配的子串。
var str="Visit Microsoft!"; document.write(str.replace(/Microsoft/, "W3School"));
案例:表单验证
QQ号:<input type="text" id="txtQQ"><span></span><br> 邮箱:<input type="text" id="txtEMail"><span></span><br> 手机:<input type="text" id="txtPhone"><span></span><br> 生日:<input type="text" id="txtBirthday"><span></span><br> 姓名:<input type="text" id="txtName"><span></span><br>
var txtQQ = document.getElementById("txtQQ");
var txtEMail = document.getElementById("txtEMail");
var txtPhone = document.getElementById("txtPhone");
var txtBirthday = document.getElementById("txtBirthday");
var txtName = document.getElementById("txtName");
?
txtQQ.onblur = function()
// 获取当前的文本框对应的span
var span = this.nextElementSibling;
var reg = /^\d5,10$/;
// 判断是否成功
if(!reg.test(this.value))
// 验证不成功
span.innerText = "请输入正确的QQ号";
span.style.color = "red";
else
// 验证成功
span.innerText = "";
span.style.color = "";
;
?
// txtPhone
txtPhone.onblur = function()
var span = this.nextElementSibling;
var reg = /^1[3456789]\d9$/;
if(!reg.test(this.value))
// 验证不成功
span.innerText = "请输入正确的手机号";
span.style.color = "red";
else
span.innerText = "";
span.style.color = "";
;
var regBirthday = /^\d4-\d1,2-\d1,2$/;
addCheckBirthday(txtBirthday, regBirthday, "请输入正确的出生日期:");
function addCheckBirthday(element, reg, tip)
element.onblur = function()
// 获取当前的文本框对应的span
var span = this.nextElementSibling;
// 判断验证是否成功
if(!regBirthday.test(this.value))
// 验证不成功
span.innerText = tip;
span.style.color = "red";
else
// 验证成功
span.innerText = "";
span.style.color = "";
;
通过元素增加自定义验证属性对表单进行验证
<form id="frm"> QQ号:<input type="text" name="txtQQ" data-rule="qq"><span></span><br> 邮箱:<input type="text" name="txtEMail" data-rule="email"><span></span><br> 手机:<input type="text" name="txtPhone" data-rule="phone"><span></span><br> 生日:<input type="text" name="txtBirthday" data-rule="date"><span></span><br> 姓名:<input type="text" name="txtName" data-rule="cn"><span></span><br> </form>
// 所有的验证规则
var rules = [
name: ‘qq‘,
reg: /^\d5,12$/,
tip: "请输入正确的QQ"
,
name: ‘email‘,
reg: /^\w+@\w+\.\w+(\.\w+)?$/,
tip: "请输入正确的邮箱地址"
,
name: ‘phone‘,
reg: /^\d11$/,
tip: "请输入正确的手机号码"
,
name: ‘date‘,
reg: /^\d4-\d1,2-\d1,2$/,
tip: "请输入正确的出生日期"
,
name: ‘cn‘,
reg: /^[\u4e00-\u9fa5]2,4$/,
tip: "请输入正确的姓名"
];
?
addCheck(‘frm‘);
//给文本框添加验证
function addCheck(formId)
var i = 0,
len = 0,
frm =document.getElementById(formId);
len = frm.children.length;
for (; i < len; i++)
var element = frm.children[i];
// 表单元素中有name属性的元素添加验证
if (element.name)
element.onblur = function ()
// 使用dataset获取data-自定义属性的值
var ruleName = this.dataset.rule;
var rule =getRuleByRuleName(rules, ruleName);
?
var span = this.nextElementSibling;
//判断验证是否成功
if(!rule.reg.test(this.value) )
//验证不成功
span.innerText = rule.tip;
span.style.color = "red";
else
//验证成功
span.innerText = "";
span.style.color = "";
?
// 根据规则的名称获取规则对象
function getRuleByRuleName(rules, ruleName)
var i = 0,
len = rules.length;
var rule = null;
for (; i < len; i++)
if (rules[i].name == ruleName)
rule = rules[i];
break;
return rule;
以上是关于JavaScript中使用正则表达式的主要内容,如果未能解决你的问题,请参考以下文章