如何编写 RegExp 来匹配第 N 个字符

How to write a RegExp to match the Nth character

有如下字符串:

2016,07,20,19,20,25

如何将此字符串转换为如下格式字符串:

2016-07-20 19:20:25

非常感谢!

数组切片的解决方案可能是这样

let parts = [];
let date = "2016,07,20,19,20,25"; 
let formatted = ((parts = date.split(",")).slice(0,3)).join("-") + ' ' + parts.slice(3).join(":")

你也可以用 String#replace 和一个函数作为第二个参数;

let date = "2016,07,20,19,20,25"; 
date.replace(/,/g, (() => {
  let count = 0;
  return (match, position) => {
    count += 1;
    if(count == 3) return ' ';
    else if(count < 3) return '-';
    else return ':';        
  });
})())

注意:两种方法都假定格式始终是提供的格式 逗号分隔的 6 个数字