问题描述
实现模板字符串插值函数 interpolate(template, data),该函数接收一个模板字符串和一个数据对象,将模板字符串中表达式的占位符替换为表达式计算后的结果,计算中的变量由数据对象提供,返回替换后的字符串。
示例:
const template =
"The sum of {{ a }} and {{ b }} is {{ a + b }} and the product is {{ a * b }}.";
const data = { a: 5, b: 3 };
const result = interpolate(template, data);
console.log(result); // 输出: "The sum of 5 and 3 is 8 and the product is 15."
前置知识
正则表达式和字符串匹配
正则表达式 [1] 是用于匹配字符串中字符组合的模式。
在 JavaScript 中,可以使用 String.prototype.match() 方法 [2] 来进行正则匹配。match() 方法接收一个正则表达式作为参数,返回一个数组或者 null 作为匹配结果:
- 如果没有匹配结果,返回
null - 如果没有开启全局匹配,返回匹配结果以及其匹配组
- 如果开启全局匹配,返回所有匹配结果
"The sum of {{ a }} and {{ b }} is ?"
.match(/{{.*}}/)
// ['{{ a }} and {{ b }}', ...]
非贪心搜索
正则表达式默认是贪心搜索,即会尝试寻找满足要求的最长的匹配结果。在匹配片段后面加上 ? 来执行片段的非贪心搜索,要求这个片段尽可能短。
"The sum of {{ a }} and {{ b }} is ?"
.match(/{{.*?}}/)
// ['{{ a }}', ...]
全局搜索
正则表达式默认只匹配第一项,在正则表达式后面加上全局标记 g 来执行全局搜索。
"The sum of {{ a }} and {{ b }} is ?"
.match(/{{.*?}}/g)
// ['{{ a }}', '{{ b }}']
捕获组
使用括号 (...) 定义捕获组。这部分匹配的副字符串被记忆。一旦被记忆,这个副字符串就可以被调用于其他用途。
"The sum of {{ a }} and {{ b }} is ?"
.match(/({{)(.*?)(}})/)
// ['{{ a }}', '{{', ' a ', '}}', ...]
// 首项为整个匹配
// 后面每一项都是一个捕获组
命名捕获组
使用括号 (?<name>...) 定义命名捕获组。可以通过名称直接获取捕获组,不用再去数是第几个捕获组了。
"The sum of {{ a }} and {{ b }} is ?"
.match(/({{)(?<var>.*?)(}})/)
// [
// '{{ a }}', '{{', ' a ', '}}', ...
// groups: {var:" a "}
// ]
// groups 属性包含命名捕获组
字符串替换
在 JavaScript 中,可以使用 String.prototype.replace() 方法 [3] 来进行正则替换。replace() 方法接收正则表达式、替换内容作为参数,返回一个字符串作为替换结果,具体语法如下:
replace(pattern, replacement)
pattern 是匹配的模式(和上文提到的字符串匹配方式完全一样),replacement 是替换成的内容。
replace()函数中pattern也可以是字符串,但是本文仅讨论pattern是正则表达式的情况。但是match()函数的参数只能是正则表达式,如果传入字符串会强制转换为正则表达式。
replacement 可以是一个字符串,字符串中的 $ 具有特殊含义,可以包括以下特殊替换模式:
- 插入字符串片段
$&插入匹配的子字符串。$`插入匹配子字符串之前的字符串片段。$'插入匹配子字符串之后的字符串片段。
- 插入捕获组
$n插入第n(索引从 1 开始)个捕获组,其中n是小于 100 的正整数。$<Name>插入名称为 Name 的命名捕获组。
- 转义
$$插入一个$。
例如
"foo2345bar".replace(/\d+/, "-$`-"); // 替换为匹配之前的字符串片段
// 'foo-foo-bar'
"foo2345bar".replace(/\d+/, "-$'-"); // 替换为匹配之后的字符串片段
// 'foo-bar-bar'
"foo2345bar".replace(/\d+/, "-$&-"); // 替换为匹配的字符串片段
// 'foo-2345-bar'
"The sum of {{ a }} and {{ b }} is ?".replace(/{{(.*?)}}/g, "<$1>"); // 使用捕获组
// 'The sum of < a > and < b > is ?'
"The sum of {{ a }} and {{ b }} is ?".replace(/({{)(?<var>.*?)(}})/g, "$<var>"); // 使用命名捕获组
// 'The sum of a and b is ?'
replacement 可以是如下函数:
function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
return replacement;
}
该函数的返回值会作为替换成的内容。
该函数可以接收以下参数:
match: 匹配的子字符串。(对应于上面的$&。)p1, p2, …, pN: 捕获组(包括命名捕获组)找到的第 n 个字符串。(对应于上面的$1、$2等。)offset: 原始字符串中匹配子字符串的偏移量。例如,如果整个字符串是'abcd',而匹配的子字符串是'bc',那么这个参数将是 1。string: 正在检查的原始字符串。groups: 一个捕获组命名组成的对象,值是匹配的部分(如果没有匹配,则为undefined)。仅在 pattern 包含至少一个命名捕获组时才存在。
"The sum of {{ a }} and {{ b }} is ?"
.replace(
/{{(.*?)}}/g,
(match, p1, offset, string, groups) => {
return p1.trim();
}
);
// 'The sum of a and b is ?'
Function() 构造函数
直接调用 Function() 构造函数 [4] 可以动态创建函数,但可能会面临一些安全性和类似于 eval() 的性能问题。
语法:
new Function(arg0, arg1, /* …, */ argN, functionBody)
-
argN(可选):被函数用作形参的名称。 -
functionBody:一个包含构成函数定义的 JavaScript 语句的字符串。
实现
匹配插值
首先就是如何匹配到插值语法的内容,获取到需要计算的表达式字符串:
使用 replace 函数,全局、非贪心匹配 {{...}},并且使用捕获组捕获 {{ 和 }} 之间的实际表达式内容。
template.replace(/{{(.+?)}}/g, replacement)
使用函数形式的 replacement,将匹配到的表达式字符串计算出来,返回替换结果。
replacement = (match, exp) => {
return /* exp 的计算结果 */
}
计算插值
下面说明如何计算表达式的值:
为了表达式能够读取 data 的属性,可以考虑将表达式放在一个函数内执行,在函数内部创建这些变量,这样表达式就能读取相应的变量了。这里使用参数的形式在函数内部创建这些变量。
具体来时,使用 Function() 构造函数创建一个新的函数,形参为 data 对象的键,函数体就是执行表达式并且返回。
const func = new Function(...Object.keys(data), `return ${exp}`);
调用函数,实参为 data 对象的值,这样就计算出了表达式的值。
func(...Object.values(data))
完整代码
function interpolate(template, data) {
return template.replace(/{{(.+?)}}/g, (match, exp) => {
const func = new Function(...Object.keys(data), `return ${exp}`);
return func(...Object.values(data));
});
}
// 测试函数功能
const template =
"The sum of {{ a }} and {{ b }} is {{ a + b }} and the product is {{ a * b }}.";
const data = { a: 5, b: 3 };
const result = interpolate(template, data);
console.log(result); // 输出: "The sum of 5 and 3 is 8 and the product is 15."
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_expressions ↩︎
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/match ↩︎
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/replace ↩︎
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/Function ↩︎