JavaScript中match方法与exec方法的异同
2016-07-21 16:03
661 查看
[code=language-javascript]var someText="web2.0 .net2.0"; var pattern=/(\w+)(\d)\.(\d)/g; var outCome_exec=pattern.exec(someText); var outCome_matc=someText.match(pattern);
[code=language-javascript]str.match(reg); reg.exec(str);
如上段代码所示,两者的调用方式不同,match方法是字符串调用的方法,而exec方法是正则表达式对象调用的方法;
两者的返回结果都是数组,既有相同之处也有不同之处。
当正则表达式没有g时,两者返回结果一致,请看下段代码:
[code=language-javascript]var someText="web2.0 .net2.0"; var pattern=/(\w+)(\d)\.(\d)/; var outCome_exec=pattern.exec(someText); var outCome_matc=someText.match(pattern); console.log(outCome_exec[0],outCome_exec[1]);//web2.0 web console.log(outCome_matc[0],outCome_matc[1]);//web2.0 web
当没有加g时
两者都只是搜索到第一个匹配项后就返回匹配到的值存在数组的下标为0的位置;
其余位置分别放置正则表达式中特别选中的数据;
并且index属性值均为第一个匹配项的下标位置;
下段代码为返回的数组模式和属性值:
[code=language-javascript]//arr:[kword,$1,$2,...] console.log(outCome_exec.index);//0 console.log(outCome_matc.index);//0 console.log(pattern.lastIndex);//0
当正则表达式加上g时
match返回装有所有匹配到的值的数组,但是没有index属性,返回的数组如下:
[code=language-javascript]arr:[kword1,kword2,kword3,...]
exec则是依次查找str中符合reg要求的第一个关键词,通过reg.lastIndex属性控制下一次查找的位置
循环调用exec
执行分3步:
1、将本次找到的关键词保存在数组的第一个元素 arr:[kword,$1,$2]
2、将本次找到的关键词的位置保存在index arr.index
3、将reg对象的lastIndex属性设置为index之后,reg.lastIndex规定下次从哪个位置开始
每次返回的数组即是arr:[kword,$1,$2];
代码如下:
[code=language-javascript]var someText="web2.0 net2.0"; var pattern=/(\w+)(\d)\.(\d)/g;//加g var result; while((result=pattern.exec(someText))!==null){ console.log(result[0]);//web2.0 net2.0 console.log(result[1]);//web net console.log(result.index);//0 7 console.log(pattern.lastIndex);//6 13 }
相关文章推荐
- JavaScript:DOM扩展
- (JS错误)document对象操作,获取对象的错误
- Gson and Json
- ajax总结
- 理解js闭包
- 读《JavaScript DOM编程艺术》笔记一
- javascript 引用类型 - Array类型
- JavaScript中的setter和getter方法!!
- 史上最全JS表单验证封装类
- ECharts图表与具体项目的简单结合
- JSTL标签库
- 常用javascript代码片段集锦
- JavaScript
- JavaScript中的匿名函数及函数的闭包
- Json解析
- JSPatch 基础用法--GitHub Bang开发文档
- [Doc ID 433386.1]JSP Pages Hanging in R12 After Removing Cached Class Files in _pages
- js事件冒泡,元素中还有其他事件
- jstack对线程信息的分析
- js 把一个函数赋给一个变量时带括号与不带括号的区别