MarkJane
12/20/2017 - 9:57 AM

js 实现字符批量替换 类型 php strtr功能

使用示例: "{greeting}! My name is { author.name }.".render({ greeting: "Hi", author: { name: "hsfzxjy" } });

function render(template, context) {

    var tokenReg = /(\\)?\{([^\{\}\\]+)(\\)?\}/g;

    return template.replace(tokenReg, function (word, slash1, token, slash2) {
        if (slash1 || slash2) {  
            return word.replace('\\', '');
        }

        var variables = token.replace(/\s/g, '').split('.');
        var currentObject = context;
        var i, length, variable;

        for (i = 0, length = variables.length; i < length; ++i) {
            variable = variables[i];
            currentObject = currentObject[variable];
            if (currentObject === undefined || currentObject === null) return '';
        }
        return currentObject;
    })
}
//将函数挂到 String 的原型链
String.prototype.render = function (context) {
    return render(this, context);
};