@ray-js/library
Version:
Ray library for browser
38 lines (37 loc) • 1.06 kB
JavaScript
import "core-js/modules/es.regexp.exec.js";
import "core-js/modules/esnext.iterator.constructor.js";
import "core-js/modules/esnext.iterator.reduce.js";
/**
* 实现 Named Groups RegExp 的正则百表达式
* ECMA 2018 的实现
* 通过 new RegExp 运算符,无法被 babel 转义
*/
export default class NamedRegexp {
/**
* 创建 Named RegExp
* @param {object} options
* @param {RegExp} options.regex 正则
* @param {Array<String>} options.groups 分组
*/
constructor(options) {
const {
regex,
groups
} = options;
this.regex = regex;
this.groups = groups;
}
exec(value) {
const matches = this.regex.exec(value);
if (!matches) return matches;
const groups = matches.reduce((result, match, index) => {
if (index > 0)
// This subtraction is required because we count
// match indexes from 1, because 0 is the entire matched string
result[this.groups[index - 1]] = match;
return result;
}, {});
matches.groups = groups;
return matches;
}
}