如何使用规则实现文本格式化?



让我从我们已经知道的开始。JS引擎发现${…}中的' '并执行其中的表达式,然后将返回的任何内容作为字符串。好的,这是内置功能:

const name = "Dick Smith";
const str = `Hello, ${name}`; 
console.log(str); // Hello, Dick Smith

现在,在这个例子中我将使用"假设我想找到every()并做同样的事情,我该如何实现呢?magicFunction()应该是什么样的?经验:

const name "Dick Smith";
const str = magicFunction("Hello, (name)");
console.log(str); // Hello, Dick Smith

细节:

这个神奇的函数获取一个字符串作为参数,并返回另一个字符串。

function magicFunction(str){
// Does some magic
return str;
}

如果需要,可以使用eval()来执行表达式。


注意:inside of()可以是任何东西,甚至是像() => {}() => ("Hello")甚至(function foo(){...})()这样的函数表达式。无论如何,它可以是JS引擎可以理解和执行的任何东西。


这是一个基本的想法,只涉及问题中提到的场景。您需要通过改进regex将其扩展到您的确切需求。

const magicFunction = (input) => {
const regex = /(?:([^()]*))/g;
const matches = input.match(regex);
matches.map(match => {
console.log(`Match: ${match}`);
console.log(`Expression: ${eval(match)}`);
input = input.replace(match, eval(match));
});
document.write(input);
}
const name = "Dheemanth Bhat";
const skill = () => "JavaScript";
const age = 27;
const rep = 1749 + 25;
const str = magicFunction("name: (name), age: (age) skill: (skill) rep: (rep).");

注意: regex的解释可以在这里找到。

最新更新