UNPKG

t-comm

Version:

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

45 lines (42 loc) 1.2 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) { var args = []; for (var _i = 1; _i < arguments.length; _i++) { args[_i - 1] = arguments[_i]; } 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 };