UNPKG

975 BJavaScriptView Raw
1
2const hasOwn = (obj, key)=> {
3 return hasOwnProperty.call(obj, key);
4};
5
6const RE_NARGS = /(%|)\{([0-9a-zA-Z_]+)\}/g;
7/**
8 * String format template
9 * - Inspired:
10 * https://github.com/Matt-Esch/string-template/index.js
11 */
12export default function(Vue) {
13
14 /**
15 * template
16 *
17 * @param {String} string
18 * @param {Array} ...args
19 * @return {String}
20 */
21
22 function template(string, ...args) {
23 if (args.length === 1 && typeof args[0] === 'object') {
24 args = args[0];
25 }
26
27 if (!args || !args.hasOwnProperty) {
28 args = {};
29 }
30
31 return string.replace(RE_NARGS, (match, prefix, i, index) => {
32 let result;
33
34 if (string[index - 1] === '{' &&
35 string[index + match.length] === '}') {
36 return i;
37 } else {
38 result = hasOwn(args, i) ? args[i] : null;
39 if (result === null || result === undefined) {
40 return '';
41 }
42
43 return result;
44 }
45 });
46 }
47
48 return template;
49}