1

Consider the following string:

const str = "I am a good boy"

At, index 7 = g At, indedx 10 = d But when I use, splice method for strings, which accept two parameters ie start index, end index, so when I use

const result = str.slice(7, 10)
console.log(result)

I am expecting it to return good but it only returns goo Why is that so, even at index 10, d is present?

According to W3 Schools

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: the starting index (position), and the ending index (position).

4
  • 1
    splice() or slice() ? Commented Aug 3, 2018 at 14:01
  • 1
    It only goes up to the index, but does not include it. Commented Aug 3, 2018 at 14:02
  • 3
    On a side note, prefer MDN to W3Schools. Commented Aug 3, 2018 at 14:03
  • Thank you, I got the point. Commented Aug 3, 2018 at 14:04

3 Answers 3

4

From the MDN documentation, the endIndex (second) parameter is the index before which to end extraction from the source string.

It's useful to have the end index be one place after the desired content because it makes doing math a little easier. If you want three characters starting at position i, you can use source.slice(i, i+3).

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

Comments

2

Think of it like how range works in maths, there are ones with inclusive boundaries and ones whose boundaries are not included i.e. a range could be one of the following,

  • closed range - (1, 10) i.e. range 2 - 9, doesn't include indices 1 and 10

  • opened range - [1, 10] i.e. range 1 - 10, includes 1 and 10.

  • half opened - [1, 10) or (1, 10] i.e. the first range starts from 1 but ends at 9, the second starts at 2 and ends at 10.

so the splice function takes a half opened range of the form [a, b) for which it includes the first but is closed at the lower boundary i.e. it doesn't include the lower boundary.

2 Comments

That's why math is always important. :)
Lol, that is the root of all explanations.
0

It looks like this. If you think of them as the places where the letters should start it makes perfect sense.

enter image description here

Comments

Your Answer

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