xinggevip

Es2015 捕获、反向引用捕获、标签函数
index.html<!DOCTYPE html> <html lang="en&qu...
扫描右侧二维码阅读全文
20
2019/06

Es2015 捕获、反向引用捕获、标签函数

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    
    <script>
        /*
            名词捕获    传统
        */
        let str = '2018-03-20';
        let red = /(\d{4})-(\d{2})-(\d{2})/;
        let dataArr = str.match(red);
        let year = dataArr[1];
        let month = dataArr[2];
        let day = dataArr[3];
        console.log(year, month, day);  // 2018 03 20
        /*
            名词捕获    Es2018(Es9)新增
        */
        let newred = /(?<years>\d{4})-(?<months>\d{2})-(?<days>\d{2})/;
        console.log(str.match(newred));
        let {years,months,days} = str.match(newred).groups;
        console.log(years, months, days);   // 2018 03 20
        
        /*
            反向引用命名捕获
        */

        let reg2 = /^(?<Strive>welcome)-\k<Strive>-\1$/;
        
        let a = 'a-a';
        let b = 'Strive-Strive';
        let c = 'welcome-welcome';
        let d = 'welcome-welcome-welcome';

        console.log(reg2.test(a));  // false
        console.log(reg2.test(b));  // false
        console.log(reg2.test(c));  // false
        console.log(reg2.test(d));  // true

        // 标签函数

        function fn(args){
            console.log(args);  // 返回一个数组,第0项是'welcome'
            return args[0].toUpperCase();
        };
        /* 
            这样调用是普通函数
            fn();
        */ 
        // 这样调用为 标签函数
        console.log(fn`welcome`);   // WELCOME


    </script>
</body>
</html>
Last modification:June 20th, 2019 at 12:01 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment