1. 程式人生 > >ES6正則拓展

ES6正則拓展

aaa 頭部 沒有 index bsp -s 所有 class section

字符串的正則方法

字符串對象共有 4 個方法,可以使用正則表達式:match()replace()search()split()

ES6 將這 4 個方法,在語言內部全部調用RegExp的實例方法,從而做到所有與正則相關的方法,全都定義在RegExp對象上

String.prototype.match 調用 RegExp.prototype[Symbol.match]

String.prototype.replace 調用 RegExp.prototype[Symbol.replace]

String.prototype.search 調用 RegExp.prototype[Symbol.search]

String.prototype.split 調用 RegExp.prototype[Symbol.split]

y 修飾符

除了u修飾符,ES6 還為正則表達式添加了y修飾符,叫做“粘連”(sticky)修飾符。

y修飾符的作用與g修飾符類似,也是全局匹配,後一次匹配都從上一次匹配成功的下一個位置開始。不同之處在於,g修飾符只要剩余位置中存在匹配就可,

y修飾符確保匹配必須從剩余的第一個位置開始,這也就是“粘連”的涵義。

var s = ‘aaa_aa_a‘;
var r1 = /a+/g;
var r2 = /a+/y;

r1.exec(s) // ["aaa"]
r2.exec(s) // ["aaa"]
r1.exec(s) // ["aa"] r2.exec(s) // null

上面代碼有兩個正則表達式,一個使用g修飾符,另一個使用y修飾符。這兩個正則表達式各執行了兩次,第一次執行的時候,兩者行為相同,剩余字符串都是_aa_a。由於g修飾沒有位置要求,所以第二次執行會返回結果,而y修飾符要求匹配必須從頭部開始,所以返回null

String.prototype.matchAll

var regex = /t(e)(st(\d?))/g;
var string = ‘test1test2test3‘;

var matches = [];
var match;
while (match = regex.exec(string)) {
  matches.push(match);
}

matches
// [ // ["test1", "e", "st1", "1", index: 0, input: "test1test2test3"], // ["test2", "e", "st2", "2", index: 5, input: "test1test2test3"], // ["test3", "e", "st3", "3", index: 10, input: "test1test2test3"] // ]

ES6正則拓展