gpt4 book ai didi

javascript - 是否有类似模板文字的东西,反之亦然?

转载 作者:行者123 更新时间:2023-11-29 23:41:37 25 4
gpt4 key购买 nike

使用模板文字很容易产生这样的东西:

const age = 22;
console.log(`Paul is ${age} years old.`)
// => Paul is 22 years old.

在从文本中解析信息时,我在问自己是否有任何可能或包反之亦然。

可以是一个函数,它检索模板和要匹配的字符串,如下所示:

const template = `Paul is ${age} years old.`;

parseTemplate(template, 'Paul is 19 years old.');
// returns e.g. {age: '19'}

不需要复杂的用例或类型解析。

最佳答案

您可以使用 destructuring from regex match

const [, age] = /^Paul is (\d+) years old.$/i.exec("Paul is 22 years old");
// age === "22"

请注意,解构模式 [, age] 中的第一个元素是空的。那是因为 RegExp.prototype.exec() 的结果是数组,第一个值是匹配的字符串。

关于javascript - 是否有类似模板文字的东西,反之亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45101461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com