Eckstein
Eckstein

Reputation: 825

Split date string with dashes

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.

Upvotes: 7

Views: 3421

Answers (4)

Nehal J Wani
Nehal J Wani

Reputation: 16629

You could also use momentjs:

> moment("20160810", "YYYYMMDD").format("YYYY-MM-DD")
'2016-08-10'

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115212

Use String#replace method

var res = '20160810'.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')

console.log(res);

Regex explanation here.

Regular expression visualization


Or with String#slice method

var str = '20160810';

var res = str.slice(0, 4) + '-' + str.slice(4,6) + '-' + str.slice(-2);

console.log(res);

Upvotes: 9

Otterbein
Otterbein

Reputation: 544

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!

Upvotes: 3

jakee
jakee

Reputation: 18556

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('-'))

Upvotes: 1

Related Questions