Wednesday 10 March 2021

How do I implement text formatting with rules?

Let me start with what we already know. JS Engine finds ${ ... } in `` and executes the expression inside, then puts whatever that returns as a string. Okay, this is build-in functionality:

const name = "Dick Smith";

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

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

Now, in this case I will use "" and let's say I want to find every () and do the same thing, how can I implement that ? How should that magicFunction() look like? EXP:

const name "Dick Smith";

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

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

Details:

That magic function gets a string as a parameter and returns another string.

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

Help

You can use eval() to execute the expression, if you want.


NOTE: inside of () can be everything, even function expressions like () => {} or () => ("Hello") or even (function foo(){...})(). Anyway, it can be everything that the JS engine can understand and execute.




from How do I implement text formatting with rules?

No comments:

Post a Comment