目录
1、原型对象打点方式
- 1、原型对象打点方式
- 2、函数传参方式
String.prototype.formatTime = function formatTime(template) { // 初始化模板 typeof template === 'undefined' ? template = '{0}年{1}月{2}日 {3}:{4}:{5}' : null; // this 要处理的字符串 // 获取日期字符串中的数字信息 let matchAry = this.match(/\d+/g); // 模板和数字的渲染(引擎机制) template = template.replace(/\{(\d+)\}/g, (x, y) => { let val = matchAry[y] || '00'; val.length < 2 ? val = '0' + val : val; return val; }); return template; } console.log('2021-03-03 13:26:23'.formatTime('{0}/{1}/{2} {3}'));2、函数传参方式
function formatTime(time, template) { // 初始化模板 typeof template === 'undefined' ? template = '{0}年{1}月{2}日 {3}:{4}:{5}' : null; // 获取日期字符串中的数字信息 let matchAry = time.match(/\d+/g); // 模板和数字的渲染(引擎机制) template = template.replace(/\{(\d+)\}/g, (x, y) => { let val = matchAry[y] || '00'; val.length < 2 ? val = '0' + val : val; return val; }); return template; } console.log(formatTime('2021-03-03 13:26:23', '{0}-{1}-{2} {3}:{4}'));