1. text()
用途:用于检验一个字符串与正则表达式是否匹配;
返回结果:Boolean类型
实例:
// 检验字符串是不是以数字结尾
var str = 'aaaa34324';
var exp = /\d$/g;
console.log(exp.test(str)); // true
2. match()
用途:用于在字符串中挑选出符合要求的值的集合;
返回结果:Array类型
实例:
// 从字符串中提取数字
var str = '现在是2020年5月19日14时14分。';
var exp = /\d+/g;
console.log(str.match(exp));
// ["2020", "5", "19", "14", "14"]
3. exec()
用途:捕获匹配到的内容,每次只会匹配一次;
返回值:Array : [ "匹配到的内容",groups: "分组的内容有几组就有几个(括号里匹配)",index: "匹配内容的起始索引", input: "原始字符串"]
var str = "现在是2020年5月19日14时14分";
var exp = /\d+/g;
var result;
while ((result = exp.exec(str)) != null) {
console.log(result); // 为数组,有几个属性
console.log('lastIndex', exp.lastIndex);// 匹配到的内容末尾索引值
}
// ["2020", index: 3, input: "现在是2020年5月19日14时14分", groups: undefined]
// lastIndex 7
// ["5", index: 8, input: "现在是2020年5月19日14时14分", groups: undefined]
// lastIndex 9
// ["19", index: 10, input: "现在是2020年5月19日14时14分", groups: undefined]
// lastIndex 12
// ["14", index: 13, input: "现在是2020年5月19日14时14分", groups: undefined]
// lastIndex 15
// ["14", index: 16, input: "现在是2020年5月19日14时14分", groups: undefined]
// lastIndex 18
4. replace()
用途:用于替换字符串中使用正则匹配到的内容;
实例:
var str = "现在是2020年5月19日4时4分";
var exp = /\d+/g;
var result = str.replace(exp, function (match, index, str) {
// match: 匹配到的内容;index:匹配到的内容初始索引值;str:原始字符串
if (match.length < 2) {
return '0' + match;
}
return match;
});
console.log(result); // '现在是2020年05月19日04时04分'