JavaScript search match test exec总结

一直对JS正则表达式中的几个函数傻傻分不清楚,search(),match(),test(),exec(),下面对四个函数进行总结

按所属对象划分

search(),match()属于String对象;test(),exec()属于RegExp对象

按函数功能划分 - 验证是否匹配

search(),test()

按函数功能划分 - 提取出匹配项

match(),exec()

String对象与RegExp对象调用函数的方式也不一样,下面是测试代码

var phone = '18814388888'
var regex = /^1[34578][0-9]{9}$/
// search()返回成功匹配的索引或-1
console.log(phone.search(regex))
// test()返回True或False
console.log(regex.test(phone))

// 都返回数组,可通过下标取值
console.log(phone.match(regex));
console.log(regex.exec(phone))

input指向原始的string字符串,index与input属性可以被调用

console.log(phone.match(regex).index); // 0
console.log(phone.match(regex).input); // 18814388888

注备:match函数与exec函数返回的都是数组。做判断时,会直接使用数组的第一个元素进行判断

console.log(phone.match(regex) === 'cjn'); // true
console.log(phone.match(regex)[0] === 'cjn'); // true

可以看出,在没有使用索引的情况下,一样能调用到第一个元素!

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值