基础

是否匹配

  1. var patt = /e/;
  2. patt.test("The best things in life are free!");

true

正则替换

  1. 'microsoft123'.replace(/microsoft/i,"Runoob")

Runoob123

有时候规则是变量。

  1. str = str.replace(RegExp(key,'g'), value);


分组查询

  1. const RE_DATE = /(\d{4})-(\d{2})-(\d{2})/;
  2. const matchObj = RE_DATE.exec('1999-12-31');
  3. const year = matchObj[1]; // 1999
  4. const month = matchObj[2]; // 12
  5. const day = matchObj[3]; // 31
  1. 0: “1999-12-31”
  2. 1: “1999”
  3. 2: “12”
  4. 3: “31”
  5. groups: undefined
  6. index: 0
  7. input: “1999-12-31”
  8. length: 4

查找出现的位置

没有java那样直接查看所有匹配的起点和终端位置。

  1. var str = "Visit Runoob!";
  2. var n = str.search(/Runoob/i);

6

示例