WorkAround Explorer Project

Can anyone explain to me what will .slice( ) method do? MDN explanation seems confusing. Thanks in advance.

Code →

Hey there, what do you find confusing of MDN explanation?
There are actually 2 explanations of .slice() method on MDN:

  1. Array.prototype.slice() - Applies to an array and gets you a second array

  2. String.prototype.slice() - Applies to a string and gives you another one!

In your case:

str = str.slice(0, i) + ',' + numStr.slice(i);

For every i you’re getting a new string composed by every substring of str from the first character (index 0) to the i character (or index i -1) plus every substring of numStr starting from the i char

1 Like

Good Day,

If we have a look at the definition of String.Prototype.Sting on MDN, it states:

The **`slice()`** method extracts a section of a string and returns it as a new string, without modifying the original string.

This method allows us to pull out a section from a string, without modifying the actual string itself.

Now for the Syntax:

str.slice(beginIndex[, endIndex])

The method takes in a beginning Index and an optional endIndex.

Now let’s look at the code example that is given

const str = 'The quick brown fox jumps over the lazy dog.';

// expected output: "the lazy dog."

In the above code, we have a string stored in str. Looking at console.log, we are using the .slice method to pull out a portion of the string. Seeing as there is only one number (index) it is considered as the beginning index. If we now count the character spaces from the start of the string, you will see that index 31 is the space just before ‘the’ and the characters that follow form ‘the lazy dog’, thus we are printing this to the console.

console.log(str.slice(4, 19));
// expected output: "quick brown fox"

Here we are starting on the 4th character (The beginning index) and since there are two values in the method, the second is considered the ending Index. In the above example, the 4th Character is the space before ‘quick’ and the 19th character is the ‘x’ in fox, thus printing ‘quick brown fox’

In essence, we are “slicing” the string at specified positions. I hope this along with the above from @usernamegiapreso helps.

1 Like

Thank you all for the amazing explanation. @codedbydom93 @usernamegiapreso