diff --git a/src/extend.js b/src/extend.js index 17cb7999f..bb903cbb3 100644 --- a/src/extend.js +++ b/src/extend.js @@ -1,5 +1,5 @@ import { warn } from './util' -import format from './format' +import Format from './format' import { getValue } from './path' @@ -12,6 +12,7 @@ import { getValue } from './path' export default function (Vue) { const { isObject } = Vue.util + const format = Format(Vue) function parseArgs (...args) { let lang = Vue.config.lang diff --git a/src/format.js b/src/format.js index 4562478dd..6ff39cc9d 100644 --- a/src/format.js +++ b/src/format.js @@ -7,36 +7,42 @@ const RE_NARGS = /(%|)\{([0-9a-zA-Z_]+)\}/g -/** - * template - * - * @param {String} string - * @param {Array} ...args - * @return {String} - */ +export default function (Vue) { + const { hasOwn } = Vue.util + + /** + * template + * + * @param {String} string + * @param {Array} ...args + * @return {String} + */ + + function template (string, ...args) { + if (args.length === 1 && typeof args[0] === 'object') { + args = args[0] + } -export default function (string, ...args) { - if (args.length === 1 && typeof args[0] === 'object') { - args = args[0] - } + if (!args || !args.hasOwnProperty) { + args = {} + } - if (!args || !args.hasOwnProperty) { - args = {} - } + return string.replace(RE_NARGS, (match, prefix, i, index) => { + let result - return string.replace(RE_NARGS, (match, prefix, i, index) => { - let result + if (string[index - 1] === '{' + && string[index + match.length] === '}') { + return i + } else { + result = hasOwn(args, i) ? args[i] : null + if (result === null || result === undefined) { + return '' + } - if (string[index - 1] === '{' - && string[index + match.length] === '}') { - return i - } else { - result = args.hasOwnProperty(i) ? args[i] : null - if (result === null || result === undefined) { - return '' + return result } + }) + } - return result - } - }) + return template } diff --git a/test/specs/format.js b/test/specs/format.js index 07b4891cb..ae0afe3e9 100644 --- a/test/specs/format.js +++ b/test/specs/format.js @@ -1,5 +1,8 @@ +import Vue from 'vue' import assert from 'power-assert' -import format from '../../src/format' +import Format from '../../src/format' + +const format = Format(Vue) describe('format', () => {