What is the best method to take a 'template' string and insert information into it.
For example:
var templateString = "Hello {name1}, my name is {name2}";
var name1 = "Phil";
var name2 = "Amy";
Would there be an easy name to insert the values where the variable name surrounded by braces is? I need this to work not only for this example (so doing it by a fixed index is not an option) but for any given template string and any given number of variables.
You can use ES2015 template literals. But, the variables should be defined before using them.
For pre-ES2015, you can use regex to replace the variables. For this, an object having the search-replace values can be created and
String#replace
with function as parameter can be used.The regex
\{([^}]*)\}
can be used to match the strings which are surrounded by the curly brackets.RegEx Explanation:
\{
: Match{
bracket literal([^}]*)
: Match anything other than}
zero or more number of times and add this in the first captured group.\}
: Match}
bracket literalg
: Global flag. Match all possible strings that follows this pattern.Note:
$0
is the complete string i.e.{foo}
and$1
is the first captured groupfoo
.ES6 has string interpolation, you can do it like this
you can use the javascript function replace: http://www.w3schools.com/jsref/jsref_replace.asp
so your code would be:
please let me know if this doesn't work.
In ES5, you could use String.replace:
Note that the use of eval is not recommended. If you set the names in an object, you could do this: