format.js 943 B

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