简体   繁体   中英

How can I replace values in an array of variables with jQuery

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?

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

DEMO

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM