UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

44 lines (41 loc) 1.25 kB
import _typeof from '@babel/runtime/helpers/typeof'; function hasOwn(obj, key) { var hasOwnProperty = Object.prototype.hasOwnProperty; return hasOwnProperty.call(obj, key); } var STRING_FORMAT_REG = /(%|)\{\{([0-9a-zA-Z_]+)\}\}/g; /** * String format template * - Inspired: * https://github.com/Matt-Esch/string-template/index.js * @param {string} string 字符串 * @param {any} args 填充选项 * @example * ```ts * stringFormat('{{likes}} people have liked this', { * likes: 123, * }); * ``` */ function stringFormat(string) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } if (args.length === 1 && _typeof(args[0]) === 'object') { args = args[0]; } if (!(args === null || args === void 0 ? void 0 : args.hasOwnProperty)) { args = {}; } return string.replace(STRING_FORMAT_REG, function (match, prefix, i, index) { if (string[index - 1] === '{' && string[index + match.length] === '}') { return i; } var result = hasOwn(args, i) ? args[i] : null; if (result === null || result === undefined) { return ''; } return result; }); } export { hasOwn, stringFormat };