关于JS中match() 和 exec() 返回值和属性的测试

语法:

rush:js;"> exec() : RegExpObject.exec(string) match() : stringObject.match(string) stringObject.match(regexp)

知识点:

exec() 是RegExp对象的方法,而 match() 是String对象的方法。 都会返回包含第一个匹配项信息的数组;或者在没有匹配项的情况下返回null。 返回的数组虽然是Array 的实例,但包含两个额外的属性:index 和 input。其中,index 表示匹配项在字符串中的位置,而 input 表示应用正则表达式的字符串。 在数组中,第一项是与整个模式匹配的字符串,其他项是与模式中的捕获组匹配的字符串(如果模式中没有捕获组,则该数组只包含一项)。

测试:

match() 的测试代码

rush:js;"> var text = "mom and dad and baby"; var pattern = /(mom and )?(dad and )?baby/; var matches = text.match(pattern);//pattern.exec(text); console.log(matches.index); console.log(matches.input); console.log(matches[0]); console.log(matches[1]); console.log(matches[2]);

match() 的测试结果截图:

对 exec() 的测试代码

rush:js;"> var text = "mom and dad and baby"; var pattern = /(mom and )?(dad and )?baby/; var matches = pattern.exec(text);//text.match(pattern); console.log(matches.index); console.log(matches.input); console.log(matches[0]); console.log(matches[1]); console.log(matches[2]);

对 exec() 的测试结果截图:

String 对象方法

方法

String 对象方法

方法

关于JS中match() 和 exec() 返回值和属性的测试就给大家介绍到这里,希望对大家有所帮助!

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...