var string = 'j1h342jg24g234j 3g24j1'; var pattern = /\d/g; var valueArray = [];//值 var indexArray = [];//位置 var temp; while((temp=pattern.exec(string)) != null){ valueArray.push(temp[0]); indexArray.push(temp.index); } //["1", "3", "4", "2", "2", "4", "2", "3", "4", "3", "2", "4", "1"] [1, 3, 4, 5, 8, 9, 11, 12, 13, 16, 18, 19, 21] console.log(valueArray,indexArray);
【test()】
test()方法用来测试正则表达式能否在字符串中找到匹配文本,接收一个字符串参数,匹配时返回true,否则返回false
var text = '000-00-000'; var pattern = /\d{3}-\d{2}-\d{4}/; if(pattern.test(text)){ console.log('The pattern was matched'); }
同样地,在调用test()方法时,会造成RegExp对象的lastIndex属性的变化。如果指定了全局模式,每次执行test()方法时,都会从字符串中的lastIndex偏移值开始尝试匹配,所以用同一个RegExp多次验证不同字符串,必须在每次调用之后,将lastIndex值置为0
var pattern = /^\d{4}-\d{2}-\d{2}$/g; console.log(pattern.test('2016-06-23'));//true console.log(pattern.test('2016-06-23'));//false //正确的做法应该是在验证不同字符串前,先将lastIndex重置为0 var pattern = /^\d{4}-\d{2}-\d{2}$/g; console.log(pattern.test('2016-06-23'));//true pattern.lastIndex = 0; console.log(pattern.test('2016-06-23'));//true
前面介绍过,javascript有9个用于存储捕获组的构造函数属性,在调用exec()或test()方法时,这些属性会被自动填充
[注意]理论上,应该保存整个表达式匹配文本的RegExp.$0并不存在,值为undefined
if(/^(\d{4})-(\d{2})-(\d{2})$/.test('2016-06-23')){ console.log(RegExp.$1);//'2016' console.log(RegExp.$2);//'06' console.log(RegExp.$3);//'23' console.log(RegExp.$0);//undefined }
以上就是小编为大家带来的javascript类型系统_正则表达式RegExp类型详解全部内容了,希望大家多多支持脚本之家~
您可能感兴趣的文章: