t-comm
Version:
专业、稳定、纯粹的工具库
54 lines (47 loc) • 1.52 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var _typeof = require('@babel/runtime/helpers/typeof');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_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__default["default"](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;
});
}
exports.hasOwn = hasOwn;
exports.stringFormat = stringFormat;