正则 null_正则表达式exec、match、test的区别

一、定义的不同

RegExp.prototype.test()

RegExp.prototype.exec()

String.prototype.match()

从MDN的定义可以看出,test和exec是正则实例的API,match是String的,这一点决定了调用方式的不同。

二、应用场景的不同

如果只是想要判断正则表达式和字符串是否匹配,用test是最简单的。

const bool = /^hello/.test('helloworld') // true

如果你不只是想要知道是否匹配,还想知道匹配的结果,那么就可以用match。

const arr = 'helloworld'.match(/^hello/)
// ['hello', index:0, input: 'helloworld', group: undefined]

如果你不仅想知道匹配结果,还想遍历匹配结果,那就可以用exec。

const reg = /foo*/g;
const str = 'table football foosball';
let res;
while ((res = reg.exec(str)) !== null) {
  console.log('==========', res);
}

执行结果如下:

e22408451d703e14da21d595795e9539.png

这里需要注意的是,如果要遍历正则结果,正则表达式一定要加上全局标识g。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值