I have a date value in this format: 20160810
I need to split it into a proper date format like so: 2016-08-10
In jquery, how would I achieve this? I can't use split() because it has to have a delimiter to reference, so I'm not sure if there's a function that can split based on the number of characters.
Use String#replace
method
var res = '20160810'.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')
console.log(res);
Regex explanation here.
Or with String#slice
method
var str = '20160810';
var res = str.slice(0, 4) + '-' + str.slice(4,6) + '-' + str.slice(-2);
console.log(res);
Good Morning!
Maybe you try to use the substr() function. This functions cuts an substring out of your string, based on an beginning and ending charindex:
var string = "20160810";
var date = string.substr(0,3)+"-"+string.substr(4,5)+"-"+string.substr(6,7);
This is also possible with an regex:
var string = "20160810";
var date = string.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3'); //2016-08-10
In the second example you use the capturing groups to capture three decimals of different lengths and replace them with themselves separated with an -
.
I hope I could help!
If you're not into doing things with RegExp:
var dateArray = '20160810'.split('')
var year = dateArray.slice(0,4).join('')
var month = dateArray.slice(4,6).join('')
var day = dateArray.slice(6).join('')
console.log([year, month, day].join('-'))
You could also use momentjs:
> moment("20160810", "YYYYMMDD").format("YYYY-MM-DD")
'2016-08-10'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With