-4

Can someone explain to me how the slice function is working on the following example? (It is a Hashtag generator)

function generateHashtag(str) {
  if (str.length >= 140 || str == "") {
    return false;
  } else {
    str = str.replace(/\s+/g, ' ');
    let capEachWord = (str) => str.trim().split(' ')
      .map(word => word[0].toUpperCase() + word.slice(1)).join('');
    let HashtagIt = (str) => '#' + str;

    return HashtagIt(capEachWord(str));
  }

}

console.log(generateHashtag("String String"))
Ele
  • 33,468
  • 7
  • 37
  • 75
Danikas
  • 3
  • 2
  • 1
    [MDN: `String.prototype.slice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice) -> _"The `slice()` method extracts a section of a string and returns it as a new string, without modifying the original string."_ – Andreas Mar 02 '19 at 12:21
  • `substring(1)` would do the same thing and be clearer. – Steven Spungin Mar 02 '19 at 12:27

1 Answers1

0

The slice method can be used for an Array or a String variable. The intention of slice method is to slice out some part of the data.

For example, if I have a string

let word = 'India';

And I want to extract dia from it, we can do it using -

let dia = word.slice(2); //output > dia, 

This will slice the string from index 2 to end of the string.

If we want to slice the middle part of the string then we can do something like -

let di = word.slice(2, 4); //output > di

The same way we can process Array as well.

Ashvin777
  • 1,446
  • 13
  • 19