【问题标题】:Is there something like template literals vice versa?是否有类似模板文字的东西,反之亦然?
【发布时间】:2017-07-14 11:06:47
【问题描述】:

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

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'}

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

【问题讨论】:

  • 为了清楚起见 - console.log(`Paul is ${age} years old.`) 将记录 Paul is 22 years old
  • 谢谢,我更新了
  • 不,什么都没有,但是如果您使用带有一些指定属性名称的模式的普通字符串,您可以相对轻松地自己构建它

标签: javascript node.js npm ecmascript-6


【解决方案1】:

您可以使用destructuring from regex match

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多