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

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

猜你喜欢

转载自blog.csdn.net/chenjineng/article/details/81302609