js正则表达式模仿 模板字符串中替换字符的方法

js正则表达式模仿 模板字符串中替换字符的方法

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>


    <script type="template/javascript" id="template">
        <table>
            <tr>
                <td id="u{{id}}">{{id}}</td>
                <td title="{{name}}">{{name}}</td>
            </tr>
        </table>
    </script>
    <script>
        // 在ES6中 是有字符串模板的 但是ES6之前呢?
        // 获取元素
        var template = document.getElementById("template");
        var tpl = template.innerText;
        // 结合对象: 
        var user = {
            id: "1234",
            name: "tony"
        };

        var str = tpl.replace(/{{(\w+)}}/g, function(match, $1) {
            return user[$1];
        });
        console.log(str)


        //   变为: 
        // `<table>
        //     <tr>
        //         <td id="u1234">1234</td>
        //         <td title="tony">tony</td>
        //     </tr>
        // </table>`
    </script>
</body>

</html>

版权声明:本文为weixin_46500485原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。