All files / str substitute.js

80% Statements 4/5
66.67% Branches 4/6
100% Functions 2/2
80% Lines 4/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24                          3x 7x       7x       2x  
/**
 * 简单模板函数
 * @method str/substitute
 * @param {String} str 要替换模板的字符串
 * @param {Object} obj 模板对应的数据对象
 * @param {RegExp} [reg=/\\?\{\{([^{}]+)\}\}/g] 解析模板的正则表达式
 * @return {String} 替换了模板的字符串
 * @example
 * var $substitute = require('@spore-ui/kit/packages/str/substitute');
 * $substitute('{{city}}欢迎您', {city:'北京'}); // '北京欢迎您'
 */
 
function substitute(str, obj, reg) {
  return str.replace(reg || (/\\?\{\{([^{}]+)\}\}/g), function (match, name) {
    Iif (match.charAt(0) === '\\') {
      return match.slice(1);
    }
    // 注意:obj[name] != null 等同于 obj[name] !== null && obj[name] !== undefined
    return (obj[name] != null) ? obj[name] : '';
  });
}
 
module.exports = substitute;