正则表达式
正则功能:匹配,提取,替换
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script>
onload = function () {
document.getElementById('btnTest').onclick = function () {
//var regExp = /^\d{6}$/;//邮政编码
var regExp = /\w+@[a-z0-9]+\..+/;
var txt = document.getElementById('txt').value;
if (regExp.test(txt)) {
alert('ok');
} else {
alert('no');
}
};
document.getElementById('btnExec').onclick = function () {
var str = 'heheh12345jjjj45679';
var regExp = /\d+/g;//加g匹配所有,不加匹配一个
while (true) {
var result = regExp.exec(str);//返回数组,无论匹配一个或多个
if (result == null) {
break;
}
alert(result);
}
};
document.getElementById('btnGroup').onclick=function(){
var str = 'heheh12345jjjj45679';
var regExp = /\d(\d)\d*/g;//提取第二个数字
while (true) {
var result = regExp.exec(str);//返回数组,无论匹配一个或多个
if (result == null) {
break;
}
alert(result);
}
};
document.getElementById('btnTrim').onclick = function () {
var str = ' hhh ';
var regExp = /\s+/g;//替换
str = str.replace(regExp, '');
alert(str);
};
}
</script>
</head>
<body>
<input type="text" name="name" value=" " id="txt"/>
<input type="button" name="name" value="test" id="btnTest" />
<input type="button" name="name" value="exec" id="btnExec" />
<input type="button" name="name" value="提取组exec" id="btnGroup" />
<input type="button" name="name" value="trim" id="btnTrim" />
</body>
</html>