正则表达式中test() exec() match()详解

1、test()  返回值为boolen

test()检测字符串是否符合正则规则,符合返回true,否则返回false

var str="1a1b1c";

var reg=/1./;

alert(reg.test(str));//true

2、exec()  如果字符串符合正则规则,则返回值为长度为1的数组,数组内存放着第一个符合规则的子串,数组的三个属性:index:符合规则子串的起始位置; lastIndex:符合规则子串的结束位置; input:保存着str


var str="1a1b1c";

var reg=/1./;

alert(reg.exec(str)[0]);//1a

alert(reg.exec(str).index)//0

alert(reg.exec(str).lastIndex)//1

alert(reg.exec(str).input)// 1a1b1c


但是,如果在正则表达式中写了g,即reg=/1./g,则多次用同一正则规则匹配同一字符串时,每一次的起始位置是上一次的lastindex位置。每次返回的数组长度还是1

var str="1a1b1c";

var reg=/1./g;

alert(reg.exec(str)[0]);//1a

alert(reg.exec(str)[0]);//1b
alert(reg.exec(str)[0]);//1c

3. match() [match()方法属于字符串的方法,上面两个方法属于正则的方法]当没有在正则表达式中写g时,match()的用法跟exec()相同,但当用了g以后,match一次性返回所有满足条件的子串,而exec()只返回一个。match()方法返回的数组同样拥有三个属性(input index lastIndex)
var str="1a1b1c";

var reg=/1./g;

alert(str.match(reg));  //["1a", "1b", "1c"]

alert(reg.exec(str));// ["1a", index: 0, input: "1a1b1c", groups: undefined]

//获取文件的扩展名

<script>
        console.log(getFileExtendingName('123.jpg'))   //.jpg
        function getFileExtendingName(filename) {
  // 文件扩展名匹配正则
  var reg = /.[^.]+$/
  var matches = reg.exec(filename)
  console.log(matches)  //[".jpg", index: 3, input: "123.jpg", groups: undefined]
  if (matches) {
    return matches[0]
  }
  return ''
}
    </script>
原文地址:https://www.cnblogs.com/hellofangfang/p/14871543.html