2

In this program, I understand (I think) that paragraph.charAT(0) = "%" checks whether the first character in paragraph is equal to %, i.e. the counting starts at 0, so charAT(0) is the first character

However, in the line, paragraph.slice(1), what does the 1 refer to? Is it slicing off the first character?, which in this case will be at 0 position?

function processParagraph(paragraph) {
  var header = 0;
  while (paragraph.charAt(0) == "%") {
    paragraph = paragraph.slice(1);
    header++;
  }

  return {type: (header == 0 ? "p" : "h" + header),
          content: paragraph};
}

show(processParagraph(paragraphs[0]));
mjmitche
  • 2,077
  • 5
  • 24
  • 31
  • 1
    see [here](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/slice). MDC is a great resource for javascript. – aaronasterling Feb 25 '11 at 03:07
  • See also [What is the difference between String.slice and String.substring in JavaScript?](http://stackoverflow.com/questions/2243824/what-is-the-difference-between-string-slice-and-string-substring-in-javascript) – Rudu Feb 25 '11 at 03:14

4 Answers4

8

It extracts a substring starting at index 1 (2nd character) of the paragraph string.

For example, consider this:

var paragraph = "Hi my name is Russell";
console.log( paragraph.slice(1) ); //returns 'i my name is Russell'
Russell Dias
  • 70,980
  • 5
  • 54
  • 71
  • thank you @Russell Dias, so if paragraph string started "%aaaaa", after slice(1), paragraph string would start "aaaaa"? – mjmitche Feb 25 '11 at 03:08
  • 1
    @mjm, to elaborate, your code as a whole slices off any number of percent signs from the start of the paragraph, when you take the loop into consideration. – Karl Bielefeldt Feb 25 '11 at 03:15
3

.slice

string.slice(beginslice[, endSlice])

Extracts a section of a string and returns a new string.

It returns everything after the first character, essentially cutting the first character off.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
1

It removes the first character from the string and returns that without altering the original string. I recommend you look at the documentation for slice.

Community
  • 1
  • 1
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
1

it's slicing off the first character (which is a "%")

generalhenry
  • 17,227
  • 4
  • 48
  • 63