wonderbeyond
7/8/2015 - 10:05 AM

format.js

/**
 * Format string with a context, using RegExp
 */

var fund = {code: '160220', name: '国泰民益'};
var result = "http://www.jjmmw.com/fund/{{code}}-{{name}}/".replace(/\{\{(\w+)\}\}/g, function(m, p1) {
	return fund[p1];
});
var format = function(str, ctx) {
    /**
     * Examples:
     *  format('hello, {name}', {name: 'wonder'})
     *  format('{0}, {1}', ['hello', 'world'])
     */
    return str.replace(/\{(\w+)\}/g, function(m, p1) {
        return ctx[p1];
    });
}