使用构造函数的方法 例: new RegExp(“\d{2}”) (标识匹配两位数组,注意构造函数传入的参数是字符串)
RegExp对象上使用匹配字符串的方法
text : 检索字符串中指定的值。返回 true 或 false。
1 2 3
var reg = /\d{2}/ var str = '20' reg.test(str) // true
exec : 检索字符串中指定的值。返回找到的值,并确定其位置。未匹配到否则返回 null。
1 2 3 4 5 6 7
// 非全局模式 var str="Hello world Hello!"; //查找"Hello" var patt=/Hello/; console.log('非全局',patt.exec(str)) // index : 0 console.log('非全局',patt.exec(str)) // index : 0 console.log('非全局',patt.exec(str)) // index : 0
1 2 3 4 5 6 7 8 9
// 全局模式 var str="Hello world Hello!"; //查找"Hello" var patt=/Hello/g; // 在全局模式下没执行一次exec便查找一次 知道查找不到返回null 出现的值的下标会保存在RegExp对象中 (此处有坑) console.log('1',patt.exec(str)) // index : 0 console.log('1',patt.exec(str)) // index : 12 console.log('1',patt.exec(str)) // null 未匹配 console.log('1',patt.exec(str)) // index :0