正则表达式
创建正则表达式对象
JavaScript中使用RegExp对象来封装一个正则表达式,并提供相关的方法和属性
字面量
let reg = /\bis\b/g; //g表示全文匹配
let str = "He is a boy. This is a dog. Where is she?";
console.log(str.replace(reg, "IS"));
构造函数
let reg = new RegExp("\\bis\\b", "g");
let str = "He is a boy. This is a dog. Where is she?";
console.log(str.replace(reg, "IS"));
修饰符
g:global,全文搜索,若不添加,则搜索到第一个匹配即停止。
i:ignore case,忽略大小写,正则表达式是大小写敏感的
let str = "He is a boy. Is he?";
console.log(str.replace(/\bis\b/gi, "0"));
围类
需要匹配数字时,可以使用范围类。
例如:[a-z]表示从 a 到 z 之间的任意字符,且包含 a 和 z 本身
let str = "a1b2c3d4z0";
console.log(str.replace(/[a-z]/g, "X"));
分组
例如: Byron{3}表示对 n 匹配 3 次,而不是 Byron。如果要对 Byron 匹配三次,就需要对其进行分组
console.log("a1b2c3d4".replace(/[a-z]\d{3}/g, "X"));
console.log("a1b2c3d4".replace(/([a-z]\d){3}/g, "X"));
反向引用
使用$n的形式引用模式中分组匹配到的文本,n为索引,从1开始。
例如:把 2020-03-04 替换成 03/04/2020。
console.log("2020-03-04"
.replace(/(\d{4})-(\d{2})-(\d{2})/g, "$2/$3/$1"));
字符串正则方法
replace(reg, function)的用法
let s1 = "a1b23d4e5".replace(/\d/g, function(match, index, origin) {
console.log(index);
return parseInt(match) + 1;
});
let s2 = "a1b23d4e5".replace(/(\d)(\w)(\d)/g,
function(match, group1, group2, group3, index, origin) {
console.log(match);
return group1 + group3;
});
test(str),用于测试字符串参数中是否存在匹配正则表达式模式的字符串,返回 true 或 false。
exec(str),使用正则表达式模式对字符串执行搜索,并将更新全部 RegExp 对象的属性以反映匹配结果。
let reg1 = /\w{1,2}/g;
console.log(reg1.test("ab,cd"));
console.log(reg1.exec("ab,cd")); console.log(reg1.source);