ES2018(ES9)新增东西
2019-10-07 本文已影响0人
Aniugel
ES2018(ES9):
1. 命名捕获
语法: (?<名字>)
let str = '2018-03-20';
let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
let {year, month ,day} = str.match(reg).groups;
console.log(year, month, day);
反向引用:
\1 \2 $1 $2
反向引用命名捕获:
语法: \k<名字>
let reg = /^(?<Strive>welcome)-\k<Strive>$/;
匹配: ‘welcome-welcome’
-------------------------------------------------
let reg = /^(?<Strive>welcome)-\k<Strive>-\1$/;
匹配: 'welcome-welcome-welcome'
替换:
$<名字>
let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
str = str.replace(reg,'$<day>/$<month>/$<year>');
console.log(str);
----------------------------------------
str = str.replace(reg, (...args)=>{
//console.log(args)
let {year, month, day} = args[args.length-1];
return `${day}/${month}/${year}`;
});
console.log(str);
2. dotAll 模式 s
之前 '.' 在正则里表示匹配任意东西, 但是不包括 \n
let reg = /\w+/gims;
3. 标签函数
function fn(){
}
fn() //这样调用就是普通函数
fn`aaa` //标签函数使用
-----------------------------------
function fn(args){
return args[0].toUpperCase();
}
console.log(fn`welcome`);
// let str = '2018-03-20'
// let reg = /(\d{4})-(\d{2})-(\d{2})/;
// console.log(str.match(reg))//["2018-03-20", "2018", "03", "20", index: 0, input: "2018-03-20", groups: undefined]
// let dateArr = str.match(reg)
// let year = dateArr[1]
// let month = dateArr[2]
// let day = dateArr[3]
// console.log(year, month, day)
// 命名捕获-- > 语法: (? <名字>)
// let str = '2018-03-20';
// let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
// let { year, month, day } = str.match(reg).groups;
// console.log(year, month, day);
// 反向引用 \1 \2
// 反向引用命名捕获:语法: \k<名字>
// let reg = /^(?<Strive>welcome)-\k<Strive>$/;
// let reg = /^(?<Strive>welcome)-\k<Strive>-\1$/;//匹配: 'welcome-welcome-welcome'
// let str = 'a-a';
// let str2 = 'Strive-Strive'
// let str3 = 'welcome-welcome'
// let str4 = 'welcome-welcome-welcome'
// console.log(reg.test(str))//false
// console.log(reg.test(str2))//false
// console.log(reg.test(str3))//true
// console.log(reg.test(str4))//false
// 替换: $<名字>
// let str = '2018-03-20'//换成20/03/2018
// let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
// // str = str.replace(reg, '$<year>/$<month>/$<day>')
// str = str.replace(reg, '$<day>/$<month>/$<year>')
// console.log(str)
// let str = '2018-03-20'//换成20/03/2018
// let reg = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
// str.replace(reg, (...args) => {
// let { year, month, day } = args[args.length - 1]
// return `${day}/${month}/${year}`
// // console.log(args)
// })
// console.log(str)
// dotAll 模式 s
// 之前 '.' 在正则里表示匹配任意东西, 但是不包括 \n
// let reg = /\w+/gims;
// let reg = /^\w+.\w+$/;
let reg = /^\w+.\w+$/s;
// let str = 'welcome-51mmr'
// let str = 'welcome]51mmr'
let str = 'welcome\n51mmr'//false
console.log(reg.test(str))
function fn(args) {
console.log(args)
return 1
}
console.log(fn`welcome`)