Mack
Mack

Reputation: 115

Combining Strings without '+'

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
}

Upvotes: 0

Views: 162

Answers (2)

Rex M
Rex M

Reputation: 144162

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.

Upvotes: 0

Mike M. Lin
Mike M. Lin

Reputation: 10072

There's sprintf() for JavaScript.

Upvotes: 4

Related Questions