将 '2021-8-31 16:21:44' 转换为 '2021年08月31日 16时21分44秒'
String.prototype.formatTime = function formatTime(template) {
typeof template === 'undefined' ? template = '{0}年{1}月{2}日 {3}时{4}分{5}秒' : null
//this为调用该方法的字符串
let arr = this.match(/((\d+))/g)
//console.log(arr) //["2021", "8", "31", "16", "21", "44"]
template = template.replace(/\{(\d+)\}/g, function (x, y) {
let val = arr[y] || '00'
val.length < 2 ? val = '0' + val : null
return val
})
return template
}
let time = '2021-8-31 16:21:44'
console.log(time.formatTime()) //2021年08月31日 16时21分44秒
String.prototype.formatTime 是将formatTime方法绑定在String对象的原型上,这样所有的字符串都可以通过str.formatTime()的方式直接调用formatTime方法了。
this.match(/((\d+))/g)
其中的this为调用该方法的字符串
match() 方法可在字符串内检索指定的值,或找到一个或多个正则表达式的匹配。返回值为存放匹配结果的数组。这个正则表达式返回的结果为template中所有数字组成的数组,即arr = ["2021", "8", "31", "16", "21", "44"]。
template.replace(/{(\d+)}/g, function (x, y) {})
这一句是把template中符合
/\{(\d+)\}/g的子字符串替换为function中的返回结果。x: 第一个参数代表的是符合正则表达式最外层
{(\d+)\}的结果, 打印出来即为{0},{1},{2},{3},{4},{5}y: 第二个参数代表的是符合正则表达式第二层
(\d+)的结果,打印出来即为0,1,2,3,4,5replace的结果:把template中的{0},{1},{2},{3},{4},{5},替换为arr[0], arr[1], arr[2], arr[3], arr[4], arr[5]