0

I come from python & if I want to print this line "Hello World" I can do this:

line = "Hello %s" % "World"

How can I combine string templates with my variables like the above?

IE, I want to combine this

var arrray = new Array( "a", "b", "c" );
var template = "<option> %s </option>";

for ( var i in array )
{
    alert( template % i ); // should show "<option> a </option>" & so on
}
Mack
  • 115
  • 4
  • 8

2 Answers2

4

There's sprintf() for JavaScript.

Mike M. Lin
  • 9,992
  • 12
  • 53
  • 62
0

Not addressing your root question, but a different (more flexible) approach to your example problem, using an MVVM framework:

<select data-bind="options: items"></select>

<script type="text/javascript">
    var viewModel = {
        items: ko.observableArray(["a", "b", "c"])
    };
    ko.applyBindings(viewModel);
</script>

This will accomplish all sorts of magical things, such as automatic/realtime binding, so when you add or remove elements from the array in the viewmodel, the <select> options automatically reflect that.

Rex M
  • 142,167
  • 33
  • 283
  • 313