Just avoid regex altogether:
var months = ['Sau', 'Vas', 'Kov', 'Bal', 'Geg', 'Bir',
'Lie', 'Rgp', 'Rgs', 'Spa', 'Lap', 'Grd']
function transformMonth (str, toText) {
str = str.split('/')
str[1] = toText ? months[str[1] - 1] : 1 + months.indexOf(str[i])
return str
}
console.log(transformMonth('2015/Sau/01', false)) // --> '2015/01/01'
console.log(transformMonth('2015/01/01', true)) // --> '2015/Sau/01'
I'm usually not a fan of regular expressions, but this one gets the job done nicely:
/ # start regex
(\d+) # capture as many digits as possible
\/ # until hitting a forward slash
(\w+) # capture as many characters as possible
\/ # until a forward slash
(\d+) # capture the remaining numbers
/ # end regex
Then, all you have to do is return the first capturing group (year) plus (1 + months.indexOf(month)
(month) plus the third capturing group (day).
var months = ['Sau', 'Vas', 'Kov', 'Bal', 'Geg', 'Bir',
'Lie', 'Rgp', 'Rgs', 'Spa', 'Lap', 'Grd']
// this transforms '2015/Sau/01 to '2015/01/01'
function toNumberMonth (str) {
return str.replace(/(\d+)\/(\w+)\/(\d+)/, function (date, year, month, day) {
return year + '/' + (1 + months.indexOf(month)) + '/' + day
})
}
Going back is just a matter of adjusting the regex to use (\d+)
in all three capturing groups:
// this transforms '2015/01/01' to '2015/Sau/01'
function toTextMonth (str) {
return str.replace(/(\d+)\/(\d+)\/(\d+)/, function (date, year, month, day) {
return year + '/' + months[month-1] + '/' + day
})
}