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:
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}}?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?
Advertisement
Answer
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