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

How do I implement text formatting with rules?

让我从我们已经知道的开始。 JS 引擎在 `` 中找到 ${ ... } 并执行其中的表达式,然后将任何 returns 作为字符串放入。好的,这是内置功能:

const name = "Dick Smith";

const str = `Hello, ${name}`; 

console.log(str); // Hello, Dick Smith

现在,在这种情况下,我将使用“”,假设我想找到每个 () 并做同样的事情,我该如何实现? magicFunction() 应该是什么样子? 经验值:

const name "Dick Smith";

const str = magicFunction("Hello, (name)");

console.log(str); // Hello, Dick Smith

详情:

那个魔法函数获取一个字符串作为参数,returns另一个字符串。

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

帮助

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


注意:() 内部的 可以是任何东西,甚至是像 () => {}() => ("Hello") 甚至 (function foo(){...})() 这样的函数表达式。反正JS引擎能理解执行的都可以。


这是仅涵盖问题中提到的场景的基本思想。您需要通过改进正则表达式将其扩展到您的确切要求。

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).");

注意:可以找到正则表达式的解释 here