erli
erli

Reputation: 408

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?

Upvotes: 4

Views: 5240

Answers (3)

Thomas Zimmermann
Thomas Zimmermann

Reputation: 1967

Another simple way to do it:

const string = "Hello {{world}}";

console.log(string.replace(/{{.*}}/, "Stack Overflow"));

Upvotes: 1

Kelvin Mandlik
Kelvin Mandlik

Reputation: 13

Generalized solution which will also work 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,
  }
));

To use Regex inbuild symbols as template, use double backslash \\ before each character. It is because above function uses template string new RegExp('\\^(.+?)\\^', 'g') to create regular expression instead RegExp constructor new RegExp(/\^(.+?)\^/g), otherwise single backslash is enough.
For example

(  => \\(
)  => \\)
(( => \\(\\(
)) => \\)\\)
^  => \\^

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37745

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

Upvotes: 8

Related Questions