3

I have this code

newRow =  "<tr><td>[[var1]]</td><td>[[var2]]</td><td>[[var3]]</td></tr>"

Now i have this array

data['var1'] ='test1';
data['var2'] ='test2';
data['var3'] ='test3';

I want to replace the above data in newRow in simplest possible way. How can I do that?

3
  • its a bit unclear, can you provide more details of what you're trying to do. Commented Oct 15, 2012 at 8:32
  • 1
    Looks like you're trying to do templating. Try mustache Commented Oct 15, 2012 at 8:34
  • You might want to read this post. Commented Oct 15, 2012 at 8:39

2 Answers 2

6
$.each(data, function(key, item) {
    newRow = newRow.replace('[[' + key + ']]', item);
});

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

thank sbuddy , that was good. One thing more , will it work if i have multiple instances of [[var1]] in the same variable. i think it will stop after replacing the first one
then change it to regex with /g modifier
5

No need for jQuery:

newRow = newRow.replace(/\[\[(\w+)\]\]/g, function($0, $1) {
  return ($1 in data ? data[$1] : '');
  // empty string as fallback, if not available in data
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.