The re implements time string formatting and implements a method on the prototype

// Step 1: Store information such as year, month and day in the specified format of the time string into an array
var str = "The 2021-02-23 10:08:50", reg = / ^ (\ d {4}) [-] / (\ d {1, 2}) [-] / (\ d {1, 2}) + (\ d {1, 2}) : (\ d {1, 2}) : (\ d {1, 2}) $/, ary = [];
str.replace(reg, function() {
    ary = ([].slice.call(arguments)).slice(1.7);
});

// Step 2: set our target time format, replace the corresponding items in the array to the specified area
var resStr = "{0} year {1} month {2} day {3} {4} minutes {5} seconds";
var reg = /{(\d+)}/g;
resStr = resStr.replace(reg, function() {
    var num = arguments[1], val = ary[num];
    val.length === 1 ? val = "0" + val : void 0;
    return val;
})
console.log(resStr)

// replace {0} with 2021: we first need to get {0}, and we also need to get the 0, which is equivalent to the index in our array, we need to replace {0} with the corresponding index.
// The contents of the re match are captured each time. If there is no grouping, usually three parameters are captured; Arguments [0] is the same as arguments[1]. Arguments [0] is the same as arguments[0]
Copy the code
// Implement a method on the String prototype that converts the specified time format String into whatever form we want
String.prototype.myFormatTime = function() {
    var reg = /^(\d{4})(? : - | \ / | \ | :) ((\ d {1, 2})? : - | \ / | \ | :) ((\ d {1, 2})? : \ s +) ((\ d {1, 2})? : - | \ / | \ | :) ((\ d {1, 2})? : - | \ / | \ | :) (\ d {1, 2}) $/ g;
    var ary = [];
    this.replace(reg, function() {
        ary = ([].slice.call(arguments)).slice(1.7);
    });
    var format = arguments[0] | |"{0} Year {1} Month {2} day {3}:{4}:{5}";
    return format.replace(/{(\d+)}/g.function() {
        var val = ary[arguments[1]].return val.length === 1 ? "0" + val : val; 
    });
}
var str = "2021/2/23 15:12:33";
console.log(str.myFormatTime("{0} Year {1} Month {2} day"));
Copy the code