简体   繁体   中英

Processing and replacing text inside double curly braces

I have a URL string:

var url = https://url.com/{{query}}/foo/{{query2}}

I have a line of code that is able to take in a string, then get an array of all the queries inside the braces:

var queries = String(url).match(/[^{\\}]+(?=})/g);

Returns: queries = ['query', 'query2']

I have a function, parse(queries) , which processes these queries and returns a list of their results:

results = ['resultOfQuery', 'resultOfQuery2']

I want to be able to take this list, and then replace the queries in the URL string with their results. The final result of this example would be:

url = https://url.com/resultOfQuery/foo/resultOfQuery2

I have two separate problems:

  1. The regex in the String.match line of code only counts for once set of curly braces, {something} . How can I modify it to look for a set of double curly braces, {{something}}?

  2. I already have the array of results. What is the best way to do the string replacement so that the queries and each of their accompanying set of double braces are replaced with their corresponding result?

You can use replace with following pattern,

{{(.+?)}}
  • {{ - Matches {{
  • (.+?) - Matches anything except newline one or more time

 let url = "https://url.com/{{query}}/foo/{{query2}}" let result = {'query': 'queryResult1', 'query2':'queryResult2' } let replaceDoubleBraces = (str,result) =>{ return str.replace(/{{(.+?)}}/g, (_,g1) => result[g1] || g1) } console.log(replaceDoubleBraces(url,result)) 

Note:- I am using result as object here so it becomes easy to find and replace values, if you can change your parse function consider returning an object from parse

Generalized solution which will also works with nested object.

function replaceText(text, obj, start = '{{', end = '}}') {
  return text.replace(new RegExp(`${start}(.+?)${end}`, 'g'), (_, part) => {
    return part.split('.')
      .reduce((o, k) => (
        o || {}
      )[k], obj);
  });
}

console.log(replaceText(
  'Hello my name is {{name.first}} {{name.last}}, age: {{age}}',
  {
    name: {
      first: 'first', last: 'last'
    },
    age: 20,
  }
));

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