该特性是非标准的,请尽量不要在生产环境中使用它!
- 非标准$1, $2, $3, $4, $5, $6, $7, $8, $9 属性是包含括号子串匹配的正则表达式的静态和只读属性。
- 这些属性可以在String.replace 方法中替换字符串. 在这种情况下, 不用在前面加上RegExp。
例:
var re = /(\w+)\s(\w+)/;
var str = 'John Smith';
str.replace(re, '$2, $1'); // "Smith John"
RegExp.$1; // "John"
RegExp.$2; // "Smith"
通用时间转换方法
export function formatDate(oldDate, fmt) {
let date = new Date()
// 可以接收String、number、Date类型,前两种当时间戳来处理
if (typeof oldDate === 'string' || typeof oldDate === 'number') {
date = new Date(+oldDate)
} else {
date = oldDate
}
// 匹配格式化的时间是否有年份
if (/(y+)/.test(fmt)) {
// RegExp.$1得到匹配有多少个y
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
// 月、日、时分秒 补0
function padLeftZero(str) {
return ('00' + str).substr(str.length)
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ''
// 判断要显示多少位
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
}
}
return fmt
}