Since we are inventing the wheel on something that would be a great feature in javascript.
I use eval() , which is not safe, but javascript is not secure. I readily admit that I'm not excellent with javascript, but I had a need, and I needed an answer, so I did one.
I decided to style my variables with @ , not $ , especially because I want to use the multi-line literal function without evaluating it until ready. So the variable syntax is @{OptionalObject.OptionalObjectN.VARIABLE_NAME}
I'm not a javascript expert, so I gladly accept improvement tips, but ...
var prsLiteral, prsRegex = /\@\{(.*?)(?!\@\{)\}/g for(i = 0; i < myResultSet.length; i++) { prsLiteral = rt.replace(prsRegex,function (match,varname) { return eval(varname + "[" + i + "]");
A very simple implementation follows
myResultSet = {totalrecords: 2, Name: ["Bob", "Stephanie"], Age: [37,22]}; rt = `My name is @{myResultSet.Name}, and I am @{myResultSet.Age}.` var prsLiteral, prsRegex = /\@\{(.*?)(?!\@\{)\}/g for(i = 0; i < myResultSet.totalrecords; i++) { prsLiteral = rt.replace(prsRegex,function (match,varname) { return eval(varname + "[" + i + "]");
In my actual implementation, I prefer to use @{{variable}} . Another set of braces. It is absurdly unlikely to happen unexpectedly. The regular expression for this will look like /\@\{\{(.*?)(?!\@\{\{)\}\}/g
To make reading easier
\@\{\{
If you have no experience with regular expressions, a pretty safe rule is to get away from every non-alphanumeric character and never avoid letters, as many escaped letters have special meaning for almost all flavors of regular expressions.
Regular Joe Jan 17 '18 at 5:33 2018-01-17 05:33
source share