一段简单的JavaScript代码,模拟Angular数据绑定信息的解析和替换
- 2020 年 4 月 2 日
- 筆記
<html> <script> function parseAndMerge(str, obj) { Object.keys(obj).forEach(key => { var regularSourceForKeyParse = `{{${key}}}`; var keyForParse = obj[key]; var oRegular = new RegExp(regularSourceForKeyParse, "g"); console.log("Regular expression source code: " + regularSourceForKeyParse); console.log("Key for Parse: " + keyForParse); console.log("regular expression instance: " + oRegular); str = str.replace(oRegular, keyForParse); console.log("current iteration end: " + str); console.log("***********************************"); }); return str; } const str = "My name is:{{name}}, I work with Java for {{time}} years"; const obj = { name: "Jerry", time: 5 }; console.log(parseAndMerge(str, obj)); </script> </html>
运行结果:
