简体   繁体   中英

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.


This is basic idea covering only the scenario mentioned in the question. You need to expand it to your exact requirement by improving the 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).");

NOTE : Explanation for the regex can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM