个人的奋斗还是历史的进程?
by ganlyun
该特性在Chrome70中测试可用
在正则表达式中使用 (matches) 即为组匹配,而命名组的格式为 (?
//before
var r=/(\d{4})-(\d{2})-(\d{2})/
var str='2015-04-13'
str.match(r)
// (4) ["2015-04-13", "2015", "04", "13", index: 0, input: "2015-04-13", groups: undefined]
// 0: "2015-04-13"
// 1: "2015"
// 2: "04"
// 3: "13"
// groups: undefined
// index: 0
// input: "2015-04-13"
// length: 4
// __proto__: Array(0)
//after
var r=/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/
var str='2015-04-13'
r.exec(str)
// (4) ["2015-04-13", "2015", "04", "13", index: 0, input: "2015-04-13", groups: {…}]
// 0: "2015-04-13"
// 1: "2015"
// 2: "04"
// 3: "13"
// groups: {year: "2015", month: "04", day: "13"}
// index: 0
// input: "2015-04-13"
// length: 4
// __proto__: Array(0)
一个非常棒的使用,在命名组之后的表达式中,可以使用 \k
var sameword = /(?<fruit>apple|orange)==\k<fruit>/
sameword.test('apple==apple') //true
sameword.test('orange==orange') //true
sameword.test('apple==orange') //false
命名组特性现在可以被用在 String 的 replace 实例方法中,我们可以轻松地交换字符串中的单词
例如,将“firstName lastName”更改为“lastName firstName”
var reg = /(?<firstname>[A-Za-z]+) (?<lastname>[A-Za-z]+)/
'gan lyun'.replace(reg,'$<lastname> $<firstname>') //注意此处参数语法格式
// "lyun gan"