有没有像模板文字反之亦然?

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

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

在parsing来自文本的信息时,我问自己是否有可能使用这个原则,或者使用这个原则反过来。

可能是一个函数,检索模板和一个string匹配,如下所示:

 const template = `Paul is ${age} years old.`; parseTemplate(template, 'Paul is 19 years old.'); // returns eg {age: '19'} 

不需要复杂的用例或typesparsing。

你可以使用正则expression式匹配解构

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

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