正則常用的幾種方法test、match、exec、replace

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分'

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章