基础
是否匹配
var patt = /e/;
patt.test("The best things in life are free!");
true
正则替换
'microsoft123'.replace(/microsoft/i,"Runoob")
Runoob123
有时候规则是变量。
str = str.replace(RegExp(key,'g'), value);
分组查询
const RE_DATE = /(\d{4})-(\d{2})-(\d{2})/;
const matchObj = RE_DATE.exec('1999-12-31');
const year = matchObj[1]; // 1999
const month = matchObj[2]; // 12
const day = matchObj[3]; // 31
- 0: “1999-12-31”
- 1: “1999”
- 2: “12”
- 3: “31”
- groups: undefined
- index: 0
- input: “1999-12-31”
- length: 4
查找出现的位置
没有java那样直接查看所有匹配的起点和终端位置。
var str = "Visit Runoob!";
var n = str.search(/Runoob/i);
6