0

I have difficulty understanding the use of slice() wrt to the following code, which doesn't fetch me the result I expected.

var cDate = "11-05-2016";
var m = cDate.slice(0,2);
var d = cDate.slice(3,2);
var y = cDate.slice(6);
console.log("Month is " + m);
console.log("Day is " + d);
console.log("Year is " + y);

This gives the following output:

Month is 11
Day is 
Year is 2016

I tried to slice with different strings. But every time I do it, it always gives me an empty string when I slice it from the middle of the string. Why is this?

6
  • 5
    "endSlice Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3)." Commented Dec 5, 2016 at 22:36
  • I want the day printed as 05. It returns an empty string Commented Dec 5, 2016 at 22:40
  • 2
    2nd parameter is not the length of slice like it is in substr. Commented Dec 5, 2016 at 22:40
  • 1
    tangentially, I would recommend .split('-') for this sort of thing rather than slice or substr as the numbers are more readable and a little less magical. var parts = cDate.split('-'); var m = parts[0]; var d = parts[1]; var y = parts[2]; Commented Dec 5, 2016 at 22:43
  • use slice when you know the indices of the characters in the string, use substr when you know the length of the substring you want Commented Dec 5, 2016 at 22:44

2 Answers 2

3

From MDN:

The slice() method extracts a section of a string and returns a new string.

The syntax of slice is:

str.slice(beginSlice[, endSlice])

Note that the endSlice is the actual position in the string (and not how many chars to get from the beginSlice).

In your example - you can't slice a string from position 3 to position 2 (because it goes backwards), so you get an empty string.

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

1 Comment

//Note that the endSlice is the actual position in the string (and not how many chars to get from the beginning// Oh Ok. I get it now. Thanks!
2

You seem to be confusing slice with substr. The arguments mean different things:

  • slice( startIndex, endIndex )
  • substr( startIndex, length )

var cDate = "11-05-2016";
var m = cDate.substr(0,2); // "11"
var d = cDate.substr(3,2); // "05"
var y = cDate.substr(6); // "2016"
console.log("Month is " + m);
console.log("Day is " + d);
console.log("Year is " + y);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.