JS函数(替换字符串中对象属性值)

function substitute(s, o) {
       return s.replace(/{([^{}]*)}/g, function (a, b) {
	    var r = o[b];
	    return typeof r === 'string' || typeof r === 'number' ? r : a;
	  }
	);
  }

  var details =  '<p><strong>From:</strong> {from}<br>';
  details += '<strong>Sent:</strong> {date}</p>';
  details += '<p><strong>Message:</strong><br>';
  details += '{message}</p>';

   var msg = substitute(details,{
      from:'userFrom',
      date:'2016-03-17',
      message:'hello'
   });

   alert(msg);

猜你喜欢

转载自liuzidong.iteye.com/blog/2283888