views:

27

answers:

1

Dear fellow coders,

Just a small question. Say I have the following HTML:

<div class="foo">
    {text}
</div>

Now we also have a JS array with 10 entries, all with a key 'text'. I want to use the snippet above as a template (snippet resides in jQuery-able webpage) for the array. Array entry goes in, HTML comes out. Here's the tricky part: I want to replace {text} with the text key from the array entry.

And all with jQuery of course ;-).

Best regards,

Reinder

+1  A: 

Try it out: http://jsfiddle.net/WZ2Vk/

(Requires jQuery 1.4 or later)

var newText = {
    text: "some new text",
    othertext: "some other new text"
}

$('div.foo').text(function(i,txt) {
    var key = txt.match(/\{([^}]+)\}/)[1];
    return newText[key];
});

You didn't give the structure of the Array, but I assume you're using it in a manner better suited for an Object. In the example above, I used and Object instead of an Array. Will work just fine with an Array.

Same example but with an Array: http://jsfiddle.net/WZ2Vk/1/

If you're replacing with actual HTML content, then change .text() to .html().

http://jsfiddle.net/WZ2Vk/2/

patrick dw
Thanks! That totally did the trick.
Reinder de Vries