1

var data = "Tue Feb 21 2012 00:00:00 GMT+0530 (IST)"

How to slice from the string like?

var x = "Tue";
var y = "Feb";
var z = "21";
var t = "2012"

Please help?

3 Answers 3

3

Just split on space

var data      = "Tue Feb 21 2012 00:00:00 GMT+0530 (IST)"
var [x,y,z,t] = data.split(' ');

console.log(x,y,z,t)

This is using destructuring to set the variables

Sign up to request clarification or add additional context in comments.

Comments

2

You could use String#split with a limit for only 4 elements.

var data = "Tue Feb 21 2012 00:00:00 GMT+0530 (IST)",
    array = data.split(' ', 4);

console.log(array);

With ES6, you could use a destruction assignment.

var data = "Tue Feb 21 2012 00:00:00 GMT+0530 (IST)",
    [x, y, z, t] = data.split(' ', 4);

console.log(x);
console.log(y);
console.log(z);
console.log(t);

Comments

1

You need to split it and not splice. Split your string by space and you get all parts divided by space in to an array.


var data = "Tue Feb 21 2012 00:00:00 GMT+0530 (IST)";
var parts = data.split(" ");
 

var x = parts[0];
var y = parts[1];

console.log(x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.