Search code examples
regexregular-language

How to write a RegExp to match the Nth character


There is a strings as below:

2016,07,20,19,20,25

How can I transfer this strings to such as this format string:

2016-07-20 19:20:25

Thank you very much!


Solution

  • A solution with array slice could be this

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

    You could also do it with String#replace and a function as the 2 argument;

    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 ':';        
      });
    })())
    

    Note: Both approaches assume that the format will always be the one provided 6 numbers seperated by commas