subash
subash

Reputation: 4137

Splitting a string in javascript

In javascript, how can I get three different substrings for the date, month, and year from the following string: "12/15/2009" ?

Upvotes: 3

Views: 8937

Answers (8)

Annie
Annie

Reputation: 6631

If you want to do any more complex date manipulation, you can also convert the string to a JavaScript Date object like this:

var date = new Date("12/15/2009");
alert(date.getFullYear());
alert(date.getMonth() + 1);
alert(date.getDate());

var newYear = new Date("1/1/2010");
alert((new Date(newYear - date)).getDate() + " days till the new year");

Upvotes: 3

Dominic Barnes
Dominic Barnes

Reputation: 28439

You can use the .split() method to break apart the string.

var strDate = "12/15/2009";
var arrDate = strDate.split('/');

var month = arrDate[0];
var day = arrDate[1];
var year = arrDate[2];

Upvotes: 4

Pascal MARTIN
Pascal MARTIN

Reputation: 401172

You can use split to split the string :

var list = "12/15/2009".split('/');
var year = list[2];
var month = list[0];
var day = list[1];
console.log(day, month, year);

Will get you :

15 12 2009

Upvotes: 1

schaermu
schaermu

Reputation: 13460

try using [yourstring].split(char splitter) to achieve the desired result (i.E. date.split("/")). This will yield a string array.

Upvotes: 1

Myles
Myles

Reputation: 21510

var splitDate = "12/15/2009".split("/");
var month = splitDate[0];
var day = splitDate[1];
var year = splitDate[2];

Upvotes: 1

YOU
YOU

Reputation: 123897

Do you want, "12","15", and "2009"? if yes following would return 3 string array.

"12/15/2009".split("/")

Upvotes: 2

Asaph
Asaph

Reputation: 162851

Try the following:

var dateString = "12/15/2009";
var dateParts = dateString.split("/");
var month = dateParts[0];
var day = dateParts[1];
var year = dateParts[2];

Upvotes: 1

Sampson
Sampson

Reputation: 268444

var date = "12/15/2009";
var parts = date.split("/");

alert(parts[0]); // 12
alert(parts[1]); // 15
alert(parts[2]); // 2009

Upvotes: 12

Related Questions