js中使用正则表达式(g模式和非g模式的区别)
2016-07-12 12:51
633 查看
js中使用正则表达式(g模式和非g模式的区别)
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>mischen</title>
<script>
//js中使用正则表达式
function test(){
//生成正则表达式对象;
// 在g模式下,正则表达式对象的exec和test方法,依赖 正则表达式对象的lastIndex属性,而lastIndex会根据我们exec
// 和test的执行 发生偏移 如果没有相应匹配 lastIndex 重归0
//在非g模式下,正则表达式对象的exec和test方法, lastIndex 不会发生偏移
//exec方法 如果正则表达式中 有分组 第一个返回的是 匹配到的字符串 后面是根据分组分别返回的匹配的 字符串
var reg=new RegExp("\\d+[a-z]+","ig"); //字符串里 \ 表示转译
var str="123abc123def";
alert(reg.lastIndex);//0
alert(reg.exec(str));//123abc
alert(reg.lastIndex);//6
alert(reg.test(str));//true
alert(reg.lastIndex);//12
}
// test();
test1();
function test1(){
//非g模式下使用 exec 和test
var reg=new RegExp("\\d+[a-z]+","i");
var str="123abc123def";
// alert(reg.lastIndex);//0
// alert(reg.exec(str));//123abc
// alert(reg.lastIndex);//0
// alert(reg.test(str));//true
// alert(reg.lastIndex);//0
// alert(reg.exec(str));//123abc
// alert(reg.lastIndex);//0
// alert(reg.test(str));//true
// alert(reg.lastIndex);//0
var reg=new RegExp("(\\d+)([a-z]+)","i");
alert(reg.exec(str));//123abc,123,abc
alert(reg.exec(str));//123abc,123,abc
}
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>mischen</title>
<script>
//js中使用正则表达式
function test(){
//生成正则表达式对象;
// 在g模式下,正则表达式对象的exec和test方法,依赖 正则表达式对象的lastIndex属性,而lastIndex会根据我们exec
// 和test的执行 发生偏移 如果没有相应匹配 lastIndex 重归0
//在非g模式下,正则表达式对象的exec和test方法, lastIndex 不会发生偏移
//exec方法 如果正则表达式中 有分组 第一个返回的是 匹配到的字符串 后面是根据分组分别返回的匹配的 字符串
var reg=new RegExp("\\d+[a-z]+","ig"); //字符串里 \ 表示转译
var str="123abc123def";
alert(reg.lastIndex);//0
alert(reg.exec(str));//123abc
alert(reg.lastIndex);//6
alert(reg.test(str));//true
alert(reg.lastIndex);//12
}
// test();
test1();
function test1(){
//非g模式下使用 exec 和test
var reg=new RegExp("\\d+[a-z]+","i");
var str="123abc123def";
// alert(reg.lastIndex);//0
// alert(reg.exec(str));//123abc
// alert(reg.lastIndex);//0
// alert(reg.test(str));//true
// alert(reg.lastIndex);//0
// alert(reg.exec(str));//123abc
// alert(reg.lastIndex);//0
// alert(reg.test(str));//true
// alert(reg.lastIndex);//0
var reg=new RegExp("(\\d+)([a-z]+)","i");
alert(reg.exec(str));//123abc,123,abc
alert(reg.exec(str));//123abc,123,abc
}
</script>
</head>
<body>
</body>
</html>
相关文章推荐
- Servelet-页面乱码(非英文字符全部是问号)
- Jsp中的自定义标签
- (js)强制不使用“兼容性视图”
- js 模拟QQ聊天窗口图片播放效果(带滚轮缩放)
- js时间戳转成日期格式
- ECMAScript 6 学习系列课程 (ES6 proxy和Reflect的相关用法)
- JS中的对象
- 判断字符串能否转json
- 理解 JavaScript 作用域和作用域链
- 读书笔记----JavaScript 权威指南(一)
- jstl标签
- js 方法
- Js作用域链及变量作用域
- Swipe JS – 移动WEB页面内容触摸滑动类库
- JS表单设置值
- url中的jsessionid解释
- 深入理解JS中的变量作用域
- javascript实现简单的收藏功能
- javascript中的return
- js 获取控件