Home > database >  Why slice(-x,0) doesn't produce expected string
Why slice(-x,0) doesn't produce expected string

Time:12-18

If I have this:

console.log('12345'.slice(-3)); // I get '345'

but when I do:

console.log('12345'.slice(-3, 0)); // I get '' (empty string).

what is the reasoning behind this? It makes no sense to me. Is there a JS API that can wrap around strings like I expect here? (I was expecting '345' again.)

CodePudding user response:

The second parameter is the index where the substring to be extracted ends (exclusive). If that index is before (or equal to) the start index (the first parameter), the result is the empty string.

As the docs say about the second parameter:

If end is positioned before or at start after normalization, nothing is extracted.

After normalization, .slice(-3) is equivalent to .slice(2), and the second parameter defaults to the length of the string, so

.slice(-3)
// equivalent to
.slice(2)

is like

.slice(2, 5) // take the substring from index 2 to index 5

and not

.slice(2, 0)

CodePudding user response:

In JavaScript, the slice() method is used to extract a section of a string and return it as a new string. The slice() method takes two arguments: a start index and an end index. The characters in the original string are included in the new string from the start index up to, but not including, the end index.

In the first example, you are using slice(-3), which means that the start index is set to the third character from the end of the string (the character at index 2). The end index is not specified, so the slice continues to the end of the string. This is why you get the expected result of '345'.

In the second example, you are using slice(-3, 0), which means that the start index is set to the third character from the end of the string (the character at index 2), and the end index is set to the first character in the string (the character at index 0). Because the end index is before the start index, the resulting string is an empty string.

If you want to slice the string in the opposite direction, from the end to the beginning, you can use a negative end index. For example:

console.log('12345'.slice(0, -3)); // '12'

This will slice the string from the beginning to the third character from the end, resulting in the string '12'.

I hope this helps to clarify the behavior of the slice() method. Let me know if you have any other questions.

  • Related